-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC_994
More file actions
72 lines (47 loc) · 1.48 KB
/
Copy pathLC_994
File metadata and controls
72 lines (47 loc) · 1.48 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.*;
class Solution {
public int orangesRotting(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
int fresh = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j] == 2)
queue.offer(new int[]{i, j});
else if (grid[i][j] == 1)
fresh++;
}
}
if (fresh == 0)
return 0;
int minutes = 0;
int[][] directions = {
{1,0},
{-1,0},
{0,1},
{0,-1}
};
while (!queue.isEmpty() && fresh > 0) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] current = queue.poll();
int row = current[0];
int col = current[1];
for (int[] dir : directions) {
int nr = row + dir[0];
int nc = col + dir[1];
if (nr < 0 || nr >= rows ||
nc < 0 || nc >= cols ||
grid[nr][nc] != 1)
continue;
grid[nr][nc] = 2;
fresh--;
queue.offer(new int[]{nr, nc});
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}
}