Skip to content

Commit c4d8a3c

Browse files
committed
Time: 3 ms (14.85%), Space: 42.5 MB (31.81%) - LeetHub
1 parent 45fae02 commit c4d8a3c

File tree

1 file changed

+28
-47
lines changed

1 file changed

+28
-47
lines changed
Lines changed: 28 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,44 @@
11
class Solution {
22
public int orangesRotting(int[][] grid) {
3-
int n = grid.length;
4-
int m = grid[0].length;
53

6-
int[][] vis = new int[n+1][m+1];
7-
int max =0;
8-
Queue<Triple> que = new LinkedList<>();
9-
for(int i=0;i<n;i++){
10-
for(int j=0;j<m;j++){
4+
//adjacency list ::
5+
Queue<List<Integer>> que = new LinkedList<>();
6+
7+
for(int i=0;i<grid.length;i++){
8+
for(int j=0;j<grid[0].length;j++){
119
if(grid[i][j]==2){
12-
que.offer(new Triple(i,j,0));
13-
vis[i][j]=1;
10+
que.offer(new ArrayList<>(Arrays.asList(i, j, 0)));
1411
}
1512
}
1613
}
17-
max =bfs(que,vis,grid);
18-
//check ::
19-
for(int i=0;i<n;i++){
20-
for(int j=0;j<m;j++){
21-
if(grid[i][j]==1 && vis[i][j]!=1){
22-
return -1;
14+
15+
int[] dy ={0,1,-1,0};
16+
int[] dx ={1,0,0,-1};
17+
18+
int mintime =0;
19+
while(!que.isEmpty()){
20+
List<Integer> list = que.poll();
21+
int x =list.get(0);
22+
int y =list.get(1);
23+
int time = list.get(2);
24+
mintime = Math.max(time , mintime);
25+
for(int i=0;i<4;i++){
26+
int nx=x+dx[i];
27+
int ny=y+dy[i];
28+
if(nx>=0 && ny>=0 && nx<grid.length && ny<grid[0].length && grid[nx][ny]==1){
29+
grid[nx][ny]=-1;
30+
que.offer(new ArrayList<>(Arrays.asList(nx, ny, time+1)));
2331
}
2432
}
2533
}
26-
return max;
2734

28-
}
29-
public int bfs(Queue<Triple> que,int[][] vis,int[][] grid){
30-
int[] dx ={0,1,0,-1};
31-
int[] dy ={1,0,-1,0};
32-
int maxi =0;
33-
while(!que.isEmpty()){
34-
Triple tt = que.poll();
35-
int x =tt.x;
36-
int y =tt.y;
37-
int time =tt.time;
38-
maxi =Math.max(time,maxi);
39-
for(int i=0;i<4;i++){
40-
int new_x = x+dx[i];
41-
int new_y =y+dy[i];
42-
43-
if(new_x<grid.length && new_x>=0 && new_y<grid[0].length && new_y>=0 && grid[new_x][new_y]==1 &&vis[new_x][new_y]!=1){
44-
que.offer(new Triple(new_x,new_y,time+1));
45-
vis[new_x][new_y]=1;
35+
for(int i=0;i<grid.length;i++){
36+
for(int j=0;j<grid[0].length;j++){
37+
if(grid[i][j]==1){
38+
return -1;
4639
}
4740
}
4841
}
49-
return maxi;
50-
}
51-
52-
53-
}
54-
class Triple{
55-
int x;
56-
int y;
57-
int time;
58-
Triple(int _x,int _y,int _time){
59-
this.x=_x;
60-
this.y=_y;
61-
this.time =_time;
42+
return mintime;
6243
}
6344
}

0 commit comments

Comments
 (0)