力扣 994. 腐烂的橘子
在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:
值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。
返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。
解析:
广度优先遍历BFS
Java:
class Solution {
public int orangesRotting(int[][] grid) {
int M = grid.length, N = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
int count = 0;
for(int row = 0; row < M; row++) {
for(int col = 0; col < N; col++) {
if(grid[row][col] == 1) {
count++;
} else if(grid[row][col] == 2) {
queue.add(new int[]{row, col});
}
}
}
int round = 0;
while(count > 0 && !queue.isEmpty()) {
round++;
int n = queue.size();
for(int i = 0; i < n; i++) {
int[] orange = queue.poll();
int row = orange[0];
int col = orange[1];
if(row - 1 >= 0 && grid[row - 1][col] == 1) {
grid[row - 1][col] = 2;
count--;
queue.add(new int[]{row - 1, col});
}
if(row + 1 < M && grid[row + 1][col] == 1) {
grid[row + 1][col] = 2;
count--;
queue.add(new int[]{row + 1, col});
}
if(col - 1 >= 0 && grid[row][col - 1] == 1) {
grid[row][col - 1] = 2;
count--;
queue.add(new int[]{row, col - 1});
}
if(col + 1 < N && grid[row][col + 1] == 1) {
grid[row][col + 1] = 2;
count--;
queue.add(new int[]{row, col + 1});
}
}
}
if(count > 0) {
return -1;
} else {
return round;
}
}
}
JavaScript:
var orangesRotting = function(grid) {
let count = 0, queue = [], total = 0, rot = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 2) {
queue.push([i, j]);
total++;
}else if (grid[i][j] === 1) {
total++;
}
}
}
if (total === 0) return 0;
while (queue.length > 0 && rot < total) {
let size = queue.length;
rot += size;
if (rot === total) return count;
for (let i = 0; i < size; i++) {
let [ti, tj] = queue.shift();
if ((ti < grid.length - 1) && grid[ti + 1][tj] === 1) {
grid[ti + 1][tj] = 2;
queue.push([ti + 1, tj])
}
if (ti > 0 && grid[ti - 1][tj] === 1) {
grid[ti - 1][tj] = 2;
queue.push([ti - 1, tj]);
}
if ((tj < grid[0].length - 1) && grid[ti][tj + 1] === 1) {
grid[ti][tj + 1] = 2;
queue.push([ti, tj + 1]);
}
if (tj > 0 && grid[ti][tj - 1] === 1) {
grid[ti][tj - 1] = 2;
queue.push([ti, tj - 1]);
}
}
count++;
}
return -1;
};