-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0994-rotting-oranges.java
More file actions
51 lines (51 loc) · 1.62 KB
/
0994-rotting-oranges.java
File metadata and controls
51 lines (51 loc) · 1.62 KB
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
class Solution {
public int orangesRotting(int[][] grid) {
int n = grid.length, m = grid[0].length;
Queue<int[]> q = new LinkedList<>();
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
if (grid[i][j] == 2) {
q.offer(new int[]{i, j});
}
}
}
int mins = 0;
while (!q.isEmpty()) {
int size = q.size();
boolean reach = false;
for (int i=0; i<size; i++) {
int [] curr = q.poll();
int x = curr[0], y = curr[1];
if (x > 0 && grid[x-1][y] == 1) {
grid[x-1][y] = 2;
q.offer(new int[]{x-1, y});
reach = true;
}
if (x < grid.length-1 && grid[x+1][y] == 1) {
grid[x+1][y] = 2;
q.offer(new int []{x+1, y});
reach = true;
}
if (y > 0 && grid[x][y-1] == 1) {
grid[x][y-1] = 2;
q.offer(new int[]{x, y-1});
reach = true;
}
if (y < grid[0].length-1 && grid[x][y+1] == 1) {
grid[x][y+1] = 2;
q.offer(new int[]{x, y+1});
reach = true;
}
}
if (reach) mins++;
else break;
}
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
if (grid[i][j] == 1)
return -1;
}
}
return mins;
}
}