题目地址:链接
思路: 使用BFS模拟腐烂过程,统计新鲜橘子数量,若无法全部腐烂则返回-1,否则返回最小分钟数。
/**
* @param {number[][]} grid
* @return {number}
*/
let dx = [0, 1, 0, -1];
let dy = [1, 0, -1, 0];
var orangesRotting = function(grid) {
let ans = 0;
let [n, m] = [grid.length, grid[0].length];
let q = [];
let freshNum = 0;
for(let i = 0; i < n; i ++) {
for(let j = 0; j < m; j ++) {
if(grid[i][j] == 2) q.push([i, j, 0]);
if(grid[i][j] == 1) freshNum ++;
}
}
while(q.length) {
let [x, y, d] = q.shift();
for(let i = 0; i < 4; i ++) {
let [nx, ny, nd] = [x + dx[i], y + dy[i], d + 1];
if(0 <= nx && nx < n && 0 <= ny && ny < m && grid[nx][ny] == 1){
ans = Math.max(ans, nd);
freshNum --;
grid[nx][ny] = 2;
q.push([nx, ny, nd]);
}
}
}
return freshNum ? -1 : ans;
};
8万+

被折叠的 条评论
为什么被折叠?



