编辑代码

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

void (async function () {
  // 存储输入的矩阵
  const matrix = [];
  // 循环读取输入,直到遇到空行
  while ((line = await readline())) {
    if (line == " ") break;
    // 将每行按空格分割并加入矩阵
    matrix.push(line.split(" "));
  }

  // 获取矩阵的尺寸
  const len = matrix.length; // 行数
  const tate = matrix[0].length; // 列数

  let ans = 0; // 记录所需的最小天数
  const queue = []; // BFS队列,存储"YES"的位置
  let need = 0; // 需要被感染的"NO"的数量

  // 遍历矩阵,统计"YES"和"NO"的数量
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < tate; j++) {
      if (matrix[i][j] == "YES") {
        // 将"YES"的位置加入队列,作为BFS的起点
        queue.push([i, j]);
      } else if (matrix[i][j] == "NO") {
        // 统计需要被感染的"NO"的数量
        need++;
      }
    }
  }

  // 定义四个方向的偏移量:右、下、左、上
  const offsets = [
    [0, 1], // 右
    [1, 0], // 下
    [0, -1], // 左
    [-1, 0], // 上
  ];

  // 特殊情况处理
  if (queue.length == 0) return console.log(-1); // 没有"YES",无法感染
  if (need == 0) return console.log(0); // 没有"NO",不需要感染

  // BFS主循环
  while (queue.length > 0) {
    // 获取当前层的节点数量
    const size = queue.length;

    // 处理当前层的所有节点
    for (let i = 0; i < size; i++) {
      // 取出队列中的第一个位置
      const [x, y] = queue.shift();

      // 向四个方向扩展
      for (const [dx, dy] of offsets) {
        // 计算新位置
        const nx = x + dx;
        const ny = y + dy;

        // 检查新位置是否有效且为"NO"
        if (
          nx >= 0 && // 不超出上边界
          nx < len && // 不超出下边界
          ny >= 0 && // 不超出左边界
          ny < tate && // 不超出右边界
          matrix[nx][ny] == "NO" // 是未感染的位置
        ) {
          // 将"NO"改为"YES",表示感染
          matrix[nx][ny] = "YES";
          // 将新位置加入队列,作为下一层的节点
          queue.push([nx, ny]);
          // 减少需要感染的"NO"的数量
          need--;
        }
      }
    }

    // 如果队列中还有下一层的节点,天数加1
    if (queue.length > 0) ans++;
  }

  // 输出结果
  if (need == 0) return console.log(ans); // 所有"NO"都被感染
  else return console.log(-1); // 还有"NO"未被感染
})();