力扣-994-腐烂的橘子

题目:
994. Rotting Oranges(medium)


解题思路:
BFS模板题。
本质是求出BFS遍历的层数。


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public int orangesRotting(int[][] grid) {
if(grid == null || grid[0] == null || grid.length == 0 || grid[0].length == 0) return -1;
Deque<Integer> q = new LinkedList<>();

int m = grid.length,n = grid[0].length;
int cnt = 0;//新鲜橘子
for(int i = 0;i<m;i++){
for(int j = 0;j<n;j++){
if(grid[i][j] == 2){
q.offer(i*n+j);//腐烂橘子入队
}else if(grid[i][j] == 1){
cnt++;//新鲜橘子加一
}
}
}

int time = 0;
while(!q.isEmpty() && cnt > 0){
time ++;//一层层的传染
int sz = q.size();
for(int i = 0;i < sz;i++){
int p = q.poll();
int x = p/n , y = p % n;//横纵坐标
if(x-1 >=0 && grid[x-1][y] == 1){//上
cnt --;
grid[x-1][y] = 2;
q.offer((x-1)*n+y);
}
if(x+1 < m && grid[x+1][y] == 1){//下
cnt --;
grid[x+1][y] = 2;
q.offer((x+1)*n+y);
}
if(y-1 >=0 && grid[x][y-1] == 1){//左
cnt --;
grid[x][y-1] = 2;
q.offer(x*n+y-1);
}
if(y+1 < n && grid[x][y+1] == 1){//右
cnt --;
grid[x][y+1] = 2;
q.offer(x*n+y+1);
}
}
}

return cnt == 0 ? time : -1;
}