-
Notifications
You must be signed in to change notification settings - Fork 0
/
48. 994. Rotting Oranges
46 lines (41 loc) · 1.64 KB
/
48. 994. Rotting Oranges
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
class Solution {
public int orangesRotting(int[][] grid) {
Queue<int[]>queue = new LinkedList<>();
int freshOranges=0;
//we will count the fresh orange and enter data in queue if rotten orange
int m = grid.length;
int n = grid[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]==2){
queue.offer(new int[]{i,j});
}else if(grid[i][j]==1){
freshOranges++;
}
}
}
int min = 0;
//for traversing the up down left right we need a direction array
int[][] directions = {{-1,0},{1,0},{0,-1},{0,1}};
//now we traverse the queue untill it is not empry and freshOrabges are changed to rotted
while(!queue.isEmpty()&& freshOranges>0){
int size = queue.size();
for(int i=0;i<size;i++){
int curr[] = queue.poll(); //current orange position
//now we traverse if any frsh orange present at left,right,top,bottom
for(int[] dir:directions){
int newRow = curr[0]+dir[0];
int newCol = curr[1]+dir[1];
//now we check new row and col is valid
if((newRow>=0 && newRow<m && newCol>=0 && newCol<n) && grid[newRow][newCol]==1){
grid[newRow][newCol]=2;
queue.offer(new int[]{newRow,newCol});
freshOranges--;
}
}
}
min++;
}
return freshOranges==0?min:-1;
}
}