994. Rotting Oranges

问题
You are given an m x n grid where each cell can have one of three values:

  • 0 representing an empty cell,
  • 1 representing a fresh orange, or
  • 2 representing a rotten orange.
    Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

由于腐烂的橘子每次都只能影响周围的橘子,因此采用BFS。
将所有腐烂的橘子加入队列。
如果没有新鲜的橘子,则返回0。
每次出队列,如果周围有新鲜的橘子存在,则将新鲜的橘子替换为腐烂并加入队列。
每个level结束后,time+1。

最后遍历一遍,如果还有新鲜的橘子,返回-1。

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
public int orangesRotting(int[][] grid) {
Queue<Integer> q = new LinkedList();
int row = grid.length;
int col = grid[0].length;
int fresh = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if ( grid[i][j] == 2){
q.add(i * col + j);
}
else if (grid[i][j] == 1){
fresh++;
}
}
}
if(fresh == 0){return 0;}

int count = q.size()-1;
int temp = 0;
int time = -1;
while(!q.isEmpty()){
int i = q.peek() / col;
int j = q.poll() % col;

if(i-1>=0 && grid[i-1][j] == 1){
grid[i-1][j] = 2;
q.add((i-1)*col+j);
temp++;
}
if(j-1>=0 && grid[i][j-1] == 1){
grid[i][j-1] = 2;
q.add(i*col+(j-1));
temp++;
}
if(i+1<row && grid[i+1][j] == 1){
grid[i+1][j] = 2;
q.add((i+1)*col+j);
temp++;
}
if(j+1<col && grid[i][j+1] == 1){
grid[i][j+1] = 2;
q.add(i*col+(j+1));
temp++;
}

if(count == 0){
count = temp;
temp = 0;
time++;
}
count--;
}

for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if ( grid[i][j] == 1){
return -1;
}
}
}
return time;

}
}

542. 01 Matrix

问题
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.

由于是搜索最近的距离,因此可以采用BFS搜索。
首先创建一个距离矩阵,将所有原矩阵为0的位置填上距离0,将其他位置填上无穷大。
使用BFS搜索,将所有0的坐标放入队列。
取出队列头元素,将其周围的距离矩阵的元素与自身距离矩阵的元素+1比较,将较小的值设置在周围的距离矩阵上。
同时,将改变数值的坐标再次放入队列。

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
class Solution{
public int[][] updateMatrix(int[][] mat) {

Queue<Integer> q = new LinkedList();
int row = mat.length;
int col = mat[0].length;
int[][] ans = new int[row][col];

for ( int i = 0; i < row; i++ ){
for (int j = 0; j < col; j++){
if (mat[i][j] == 0){
ans[i][j] = 0;
q.add(i*col + j);
}
else{
ans[i][j] = Integer.MAX_VALUE;
}
}
}


while(!q.isEmpty()){
int i = q.peek() / col;
int j = q.poll() % col;

if(i-1 >= 0 && ans[i][j]+1 < ans[i-1][j]){
ans[i-1][j] = ans[i][j]+1;
q.add((i-1)*col + j);
}
if(i+1 < row && ans[i][j]+1 < ans[i+1][j]){
ans[i+1][j] = ans[i][j]+1;
q.add((i+1)*col + j);
}
if(j-1 >= 0 && ans[i][j]+1 < ans[i][j-1]){
ans[i][j-1] = ans[i][j]+1;
q.add(i*col + (j-1));
}
if(j+1 < col && ans[i][j]+1 < ans[i][j+1]){
ans[i][j+1] = ans[i][j]+1;
q.add(i*col + (j+1));
}
}
return ans;
}
}