-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRottingOranges.java
More file actions
65 lines (48 loc) · 1.83 KB
/
Copy pathRottingOranges.java
File metadata and controls
65 lines (48 loc) · 1.83 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
package LeetcodePractice;
import java.util.*;
public class RottingOranges {
public int orangesRotting(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
int freshOranges = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r][c] == 2) {
queue.offer(new int[]{r, c});
} else if (grid[r][c] == 1) {
freshOranges++;
}
}
}
if (freshOranges == 0) return 0;
int minutes = 0;
int[][] dirs = {{-1,0}, {1,0}, {0,-1}, {0,1}};
while (!queue.isEmpty()) {
int size = queue.size();
boolean rottedThisMinute = false;
for (int i = 0; i < size; i++) {
int[] curr = queue.poll();
for (int[] d : dirs) {
int r = curr[0] + d[0], c = curr[1] + d[1];
if (r >= 0 && r < rows && c >= 0 && c < cols && grid[r][c] == 1) {
grid[r][c] = 2;
queue.offer(new int[]{r, c});
freshOranges--;
rottedThisMinute = true;
}
}
}
if (rottedThisMinute) minutes++;
}
return freshOranges == 0 ? minutes : -1;
}
public static void main(String[] args) {
RottingOranges solver = new RottingOranges();
int[][] grid1 = {{2,1,1},{1,1,0},{0,1,1}};
System.out.println(solver.orangesRotting(grid1));
int[][] grid2 = {{2,1,1},{0,1,1},{1,0,1}};
System.out.println(solver.orangesRotting(grid2));
int[][] grid3 = {{0,2}};
System.out.println(solver.orangesRotting(grid3));
}
}