问题:西红柿在 JavaScript 中腐烂所需的时间
问题
我们需要编写一个JavaScript函数,该函数接受二维数字数组arr作为唯一参数。
数组中的数字可以是-
值0代表一个空单元格;
值1代表新鲜番茄;
值2代表一个烂番茄。
每分钟,与腐烂番茄相邻(4个方向)的任何新鲜番茄都会腐烂。
我们的函数应该返回在没有细胞有新鲜番茄之前必须经过的最小分钟数。如果这是不可能的,我们应该返回-1。
例如,如果函数的输入是-
const arr = [ [2, 1, 1], [1, 1, 0], [0, 1, 1] ];
那么输出应该是-
const output = 4;
输出说明
[ [2, 2, 1], [2, 1, 0], [0, 1, 1] ]
[ [2, 2, 2], [2, 2, 0], [0, 1, 1] ]
[ [2, 2, 2], [2, 2, 0], [0, 2, 1] ]
[ [2, 2, 2], [2, 2, 0], [0, 2, 2] ]
示例
此代码将是-
const arr = [ [2, 1, 1], [1, 1, 0], [0, 1, 1] ]; const timeToRot = (arr = []) => { let fresh = 0; let count = -1; let curr = []; for(let i = 0; i < arr.length; i++){ for(let j = 0; j < arr[i].length; j++){ if(arr[i][j] === 1){ fresh += 1; }; if(arr[i][j] === 2){ curr.push([i, j]); }; }; }; if(!fresh){ return 0; }; while(curr.length > 0){ count += 1; const next = []; const rotten = (i, j) => { arr[i][j] = 2 next.push([i, j]) fresh -= 1 }; for(const [i, j] of curr){ if (arr[i - 1] && arr[i - 1][j] === 1) { rotten(i - 1, j); }; if (arr[i + 1] && arr[i + 1][j] === 1) { rotten(i + 1, j); }; if (arr[i][j - 1] === 1) { rotten(i, j - 1); }; if (arr[i][j + 1] === 1) { rotten(i, j + 1); }; } curr = next }; return fresh === 0 ? count : -1; }; console.log(timeToRot(arr));输出结果
控制台中的输出将是-
4