-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathRotting Oranges.java
45 lines (44 loc) · 1.26 KB
/
Rotting Oranges.java
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
class Solution {
class Pair{
int i;
int j;
int t;
public Pair(int i,int j,int t){
this.i = i;
this.j = j;
this.t = t;
}
}
int ans = 0;
final int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};
public int orangesRotting(int[][] grid) {
int countFresh = 0;
Queue<Pair> q = new LinkedList<>();
for(int i=0;i<grid.length;i++){
for(int j = 0;j<grid[0].length;j++){
if(grid[i][j] == 2){
q.offer(new Pair(i,j,0));
}else if(grid[i][j] == 1){
countFresh++;
}
}
}
int count = 0;
while(q.size() != 0){
Pair temp = q.poll();
ans = Math.max(ans,temp.t);
for(int[] d : dir){
int r = temp.i + d[0];
int c = temp.j + d[1];
int t = temp.t +1;
if(r >= 0 && c >= 0 && r <grid.length && c < grid[0].length && grid[r][c] == 1){
q.offer(new Pair(r,c,t));
grid[r][c] = 2;
count++;
}
}
}
if(count != countFresh) return -1;
return ans;
}
}