-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
33 lines (33 loc) · 1.12 KB
/
Solution.java
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
class Solution {
public int orangesRotting(int[][] grid) {
int m = grid.length, n = grid[0].length;
Deque<int[]> q = new ArrayDeque<>();
int cnt = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
++cnt;
} else if (grid[i][j] == 2) {
q.offer(new int[] {i, j});
}
}
}
final int[] dirs = {-1, 0, 1, 0, -1};
for (int ans = 1; !q.isEmpty() && cnt > 0; ++ans) {
for (int k = q.size(); k > 0; --k) {
var p = q.poll();
for (int d = 0; d < 4; ++d) {
int x = p[0] + dirs[d], y = p[1] + dirs[d + 1];
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
grid[x][y] = 2;
q.offer(new int[] {x, y});
if (--cnt == 0) {
return ans;
}
}
}
}
}
return cnt > 0 ? -1 : 0;
}
}