
java
class Solution {
public int orangesRotting(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
//盛放腐烂橘子坐标
Queue<int[]> queue = new LinkedList<>();
//记录新鲜橘子数量
int freshCount = 0;
//遍历整个网格,将腐烂橘子放入队列同时统计新鲜数量
for(int r = 0; r < rows; r++){
for(int c = 0; c < cols; c++){
if(grid[r][c] == 2){
queue.offer(new int[]{r,c});
}else if(grid[r][c] == 1){
freshCount++;
}
}
}
if(freshCount == 0){
return 0;
}
int minutes = 0;
//上下左右移动的数组
int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
while(!queue.isEmpty() && freshCount > 0){
minutes++;
//当前队列中腐烂橘子数量
int size = queue.size();
for(int i = 0; i < size; i++){
//取出腐烂橘子的坐标
int[] zombie = queue.poll();
int r = zombie[0];
int c = zombie[1];
//开始向四周橘子腐烂
for(int[] dir : dirs){
int nextR = r + dir[0];
int nextC = c + dir[1];
if(nextR < 0 || nextR >= rows || nextC < 0 || nextC >= cols
|| grid[nextR][nextC] != 1){
continue;
}
grid[nextR][nextC] = 2;
freshCount--;
queue.offer(new int[]{nextR,nextC});
}
}
}
return freshCount == 0 ? minutes : -1;
}
}
解题思路:
定义一个盛放一维数组的队列,用于盛放腐烂的橘子;定义一个记录新鲜橘子数量的变量。
双层循环将腐烂橘子入队,同时记录新鲜橘子数量。
循环将腐烂橘子向上下左右四个方向扩散,同时设置边界条件。
新的腐烂橘子入队。
找连通块、算面积、数有几座岛,用DFS
求最短路径、求扩散层数、求最小时间,用BFS