-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRottenOranges.java
More file actions
67 lines (54 loc) · 1.82 KB
/
Copy pathRottenOranges.java
File metadata and controls
67 lines (54 loc) · 1.82 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
package src.Arrays;
import java.util.ArrayDeque;
import java.util.Queue;
/*
https://medium.com/trick-the-interviwer/rotting-oranges-e09ca22f6e24
*/
public class RottenOranges {
private int[] X = new int[]{-1,1,0,0};
private int[] Y = new int[]{0,0, -1,1};
private boolean isValidGrid(int x, int y, int row, int col) {
return (x >=0 && y >= 0 && x < row && y < col);
}
public int solution(int[][] grid) {
if (grid == null)
return 0;
int freshOranges = 0;
int time = 0;
Queue<Integer> queue = new ArrayDeque<>();
for (var i = 0; i < grid.length; i++) {
for (var j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 2) {
queue.add(i * grid[0].length + j);
} else if (grid[i][j] == 1) {
freshOranges++;
}
}
}
if (freshOranges == 0)
return 0;
if (queue.isEmpty())
return -1;
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
int top = queue.poll();
int x = top / grid[0].length;
int y = top % grid[0].length;
// verify the neighbour oranges
for (var i = 0; i < 4; i++) {
int newR = x + X[i];
int newC = y + Y[i];
if (isValidGrid(newR, newC, grid.length, grid[0].length) && grid[newR][newC] == 1) {
grid[newR][newC] = 2;
freshOranges--;
queue.add(newR * grid[0].length + newC);
}
}
}
if (queue.size() > 0)
time++;
}
return freshOranges == 0 ? time : -1;
}
}