编辑代码

// const { xcode } = require("react-syntax-highlighter/dist/esm/styles/hljs");

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
  // 输入
  const arr = (await readline()).split(",").map(Number);
  const n = Math.sqrt(arr.length, 2);
  const matrix = [];
  for (let i = 0; i < n; i++) {
    matrix.push(arr.slice(i * n, (i + 1) * n));
  }
  // 初始化队列
  const queue = [];
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      if (matrix[i][j] === 1) {
        queue.push([i, j]);
      }
    }
  }
  // 偏移量
  const offsets = [
    [0, 1],
    [1, 0],
    [0, -1],
    [-1, 0],
  ];
  // 健康人数
  let healthy = arr.length - queue.length;
  // 时间
  let time = 0;
  // 遍历队列
  while (queue.length) {
    // 当前队列大小
    let size = queue.length;
    // 遍历当前队列
    for (let i = 0; i < size; i++) {
      // 出队
      const [x, y] = queue.shift();
      // 遍历偏移量
      for (let [offsetX, offsetY] of offsets) {
        // 新坐标
        const newX = x + offsetX;
        const newY = y + offsetY;
        // 判断新坐标是否在矩阵内且为健康人
        if (
          newX >= 0 &&
          newX < n &&
          newY >= 0 &&
          newY < n &&
          matrix[newX][newY] === 0
        ) {
          // 感染健康人
          matrix[newX][newY] = 1;
          // 入队
          queue.push([newX, newY]);
          // 健康人数减一
          healthy--;
        }
      }
    }
    // 时间加一
    time++;
    if (healthy === 0) break;
  }
  console.log(time);
})();