994. 腐烂的橘子
在给定的 m x n 网格 grid 中,每个单元格可以有以下三个值之一:
值 0 代表空单元格;
值 1 代表新鲜橘子;
值 2 代表腐烂的橘子。
每分钟,腐烂的橘子 周围 4 个方向上相邻 的新鲜橘子都会腐烂。
返回 直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1 。
思路:多源的DFS。将二维数组的位置进行编码,变成一维的并保存在队列中。使用一个Map保存每个编码位置的深度。
先将每个发霉的橘子的位置存入队列中,并将对应的深度设为1。遍历队列中每个元素的上下左右四个位置,成立则保存其编码位置在队列中,并将其深度设为父节点深度+1。答案为当前节点深度。并更新橘子的状态。
class Solution {
public int orangesRotting(int[][] grid) {
int[] r = new int[]{-1,0, 0,1};
int[] c = new int[]{ 0,1,-1,0};
// 保存位置编码
Queue<Integer> q = new ArrayDeque();
Map<Integer, Integer> depth = new HashMap();
int ans = 0;
int R = grid.length;
int C = grid[0].length;
for(int i=0; i<R; i++) {
for(int j=0; j<C; j++) {
if(grid[i][j] == 2) {
int code = i*C + j;
q.offer(code);
depth.put(code, 0);
}
}
}
while(!q.isEmpty()) {
int code = q.remove();
int x = code/C;
int y = code%C;
for(int i=0; i<4; i++) {
int xx = x + r[i];
int yy = y + c[i];
if(xx>=0 && xx<R && yy>=0 && yy<C && grid[xx][yy] == 1) {
grid[xx][yy] = 2;
int newc = xx*C + yy;
q.offer(newc);
depth.put(newc, depth.get(code)+1);
ans = depth.get(newc);
}
}
}
for(int[] row:grid) {
for(int val:row) {
if(val == 1) {
return -1;
}
}
}
return ans;
}
}