题目描述:
在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:
- 值
0代表空单元格; - 值
1代表新鲜橘子; - 值
2代表腐烂的橘子。
每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。
返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。

错误思路:
java
class Solution {
public int orangesRotting(int[][] grid) {
int count = 0;
int res = 0;
int n = grid.length;
int m = grid[0].length;
int[][] visit = new int[n][m];
for(int i = 0; i < n;i++){
for(int j = 0; j < m;j++){
visit[i][j] = 1;
if(grid[i][j] == 2){
int temp = 0;
temp += dfs(grid,i+1,j,visit);
temp += dfs(grid,i,j+1,visit);
temp += dfs(grid,i-1,j,visit);
temp += dfs(grid,i,j-1,visit);
if(temp > 0){
res = 1;
count++;
}
}
}
}
for(int i = 0; i < n;i++){
for(int j = 0; j < m;j++){
if(grid[i][j] == 1){
return -1;
}
}
}
if(res == 0){
return 0;
}else{
if(count < 1){
return -1;
}else{
return count;
}
}
}
public int dfs(int[][] grid,int i,int j,int[][] visit){
if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == 0 || visit[i][j] == 1){
return 0;
}
if(grid[i][j] == 1){
grid[i][j] = 2;
visit[i][j] = 1;
return 1;
}
return 0;
}
}
官方题解:
java
public int orangesRotting(int[][] grid) {
int M = grid.length;
int N = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
int count = 0; // count 表示新鲜橘子的数量
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
if (grid[r][c] == 1) {
count++;
} else if (grid[r][c] == 2) {
queue.add(new int[]{r, c});
}
}
}
int round = 0; // round 表示腐烂的轮数,或者分钟数
while (count > 0 && !queue.isEmpty()) {
round++;
int n = queue.size();
for (int i = 0; i < n; i++) {
int[] orange = queue.poll();
int r = orange[0];
int c = orange[1];
if (r-1 >= 0 && grid[r-1][c] == 1) {
grid[r-1][c] = 2;
count--;
queue.add(new int[]{r-1, c});
}
if (r+1 < M && grid[r+1][c] == 1) {
grid[r+1][c] = 2;
count--;
queue.add(new int[]{r+1, c});
}
if (c-1 >= 0 && grid[r][c-1] == 1) {
grid[r][c-1] = 2;
count--;
queue.add(new int[]{r, c-1});
}
if (c+1 < N && grid[r][c+1] == 1) {
grid[r][c+1] = 2;
count--;
queue.add(new int[]{r, c+1});
}
}
}
if (count > 0) {
return -1;
} else {
return round;
}
}
反思复盘:
1.原本以为这题和岛屿数量类似的思路,但是不同的是,每次腐烂扩散需要考虑所有腐烂的橘子,如果不用队列辅助是做不出来的。
2.题解巧妙的使用count计算新鲜橘子的数量,同时腐烂扩散的时候递减,如果最后有橘子没有,被扩散到,说明要返回-1,通过int[]数组记录腐烂橘子的横纵坐标,便于四个方向扩散。