-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRottingOranges.java
More file actions
55 lines (46 loc) · 1.55 KB
/
RottingOranges.java
File metadata and controls
55 lines (46 loc) · 1.55 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
package Recursion;
import java.util.ArrayDeque;
import java.util.Deque;
public class RottingOranges {
public int orangesRotting(int[][] grid) {
if(grid.length==0) return -1;
int rows= grid.length;
int cols = grid[0].length;
int result =0;
int freshOranges =0;
Deque<int[]> queue = new ArrayDeque<>();
for(int i=0;i< grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j]==1){
freshOranges++;
}
else if(grid[i][j]==2){
queue.add(new int[]{i, j});
}
}
}
while(!queue.isEmpty() && freshOranges!=0){
int queueLength = queue.size();
result++;
for (int i = 0; i < queueLength; i++) {
int[] rotten = queue.poll();
int r = rotten[0], c = rotten[1];
int[][] neighbors = {{r, c + 1}, {r, c - 1}, {r + 1, c}, {r - 1, c}};
for (int j = 0; j < 4; j++) {
int newR = neighbors[j][0], newC = neighbors[j][1];
if (Math.min(newR, newC) < 0 || newR == rows || newC == cols
|| grid[newR][newC] != 1) {
continue;
}
freshOranges--;
queue.add(neighbors[j]);
grid[newR][newC] = 2;
}
}
}
if(freshOranges>0){
return -1;
}
return result;
}
}