编辑代码

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
  const [len, tate] = (await readline()).split(" ").map(Number);
  const matrix = [];
  for (let i = 0; i < len; i++) {
    matrix[i] = (await readline()).split(" ").map(Number);
  }
  const offsets = [
    [-1, -1],
    [-1, 0],
    [-1, 1],
    [0, -1],
    [0, 1],
    [1, -1],
    [1, 0],
    [1, 1],
  ];
  const bfs = (i, j) => {
    // 坐标入栈
    const queue = [];
    queue.push([i, j]);
    while (queue.length > 0) {
      const [x, y] = queue.shift();
      // 四周的1入队
      for (const offset of offsets) {
        const newX = x + offset[0];
        const newY = y + offset[1];
        if (
          newX >= 0 &&
          newX < len &&
          newY >= 0 &&
          newY < tate &&
          matrix[newX][newY] == 1
        ) {
          // 标记为0,防止再次入队
          matrix[newX][newY] = 0;
          queue.push([newX, newY]);
        }
      }
    }
  };
  // 统计1的数量并执行bfs
  let count = 0;
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < tate; j++) {
      if (matrix[i][j] == 1) {
        count++;
        bfs(i, j);
      }
    }
  }
  console.log(count);
})();
// };