@@ -2,31 +2,39 @@ class Solution {
2
2
private static final int [][] DIRS = {{1 , 0 }, {0 , 1 }, {-1 , 0 }, {0 , -1 }};
3
3
4
4
public int closedIsland (int [][] grid ) {
5
- int numberOfClosedIslands = 0 ;
6
- for (int i = 0 ; i < grid .length ; i ++){
7
- for (int j = 0 ; j < grid [0 ].length ; j ++){
8
- if (grid [i ][j ] == 0 ){
9
- if (surroundsSuccessfully (grid , i , j )) {
10
- numberOfClosedIslands ++;
11
- }
5
+ int closedIslandCount = 0 ;
6
+ for (int i = 0 ; i < grid .length ; i ++) {
7
+ for (int j = 0 ; j < grid [0 ].length ; j ++) {
8
+ if (grid [i ][j ] == 0 && isSurroundedSuccessfully (grid , i , j )) {
9
+ closedIslandCount ++;
12
10
}
13
11
}
14
12
}
15
- return numberOfClosedIslands ;
13
+ return closedIslandCount ;
16
14
}
17
-
18
- private boolean surroundsSuccessfully (int [][] grid , int x , int y ) {
19
- if (x < 0 || x >= grid .length || y < 0 || y >= grid [0 ].length ) {
20
- return false ;
21
- }
22
- if (grid [x ][y ] == 1 ) {
23
- return true ;
24
- }
25
- grid [x ][y ] = 1 ;
26
- boolean result = true ;
27
- for (int [] dir : DIRS ){
28
- result = result & surroundsSuccessfully (grid , x + dir [0 ], y + dir [1 ]);
15
+
16
+ private boolean isSurroundedSuccessfully (int [][] grid , int i , int j ) {
17
+ Queue <int []> queue = new LinkedList <>();
18
+ queue .add (new int []{i , j });
19
+ boolean surroundingCheck = true ;
20
+ while (!queue .isEmpty ()) {
21
+ int [] removed = queue .remove ();
22
+ int x = removed [0 ];
23
+ int y = removed [1 ];
24
+ if (x < 0 || y < 0 || x >= grid .length || y >= grid [0 ].length ) {
25
+ surroundingCheck = false ;
26
+ continue ;
27
+ }
28
+ if (grid [x ][y ] == 1 ) {
29
+ continue ;
30
+ }
31
+ grid [x ][y ] = 1 ;
32
+ for (int [] dir : DIRS ) {
33
+ int newX = x + dir [0 ];
34
+ int newY = y + dir [1 ];
35
+ queue .add (new int []{newX , newY });
36
+ }
29
37
}
30
- return result ;
38
+ return surroundingCheck ;
31
39
}
32
40
}
0 commit comments