1
1
class Solution {
2
2
public int orangesRotting (int [][] grid ) {
3
- int n = grid .length ;
4
- int m = grid [0 ].length ;
5
3
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 ++){
11
9
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 )));
14
11
}
15
12
}
16
13
}
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 )));
23
31
}
24
32
}
25
33
}
26
- return max ;
27
34
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 ;
46
39
}
47
40
}
48
41
}
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 ;
62
43
}
63
44
}
0 commit comments