File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int numIslands (char [][] grid ) {
3
+ Queue <Pair > island = new LinkedList <>();
4
+ int N = grid .length ;
5
+ int M = grid [0 ].length ;
6
+ boolean [][] visited = new boolean [N ][M ];
7
+ int count = 0 ;
8
+
9
+ for (int i = 0 ; i < N ; i ++){
10
+ for (int j = 0 ; j < M ; j ++){
11
+ if (!visited [i ][j ] && grid [i ][j ] == '1' ){
12
+ island .offer (new Pair (i , j ));
13
+ visited [i ][j ] = true ;
14
+ bfs (grid , visited , island );
15
+ count ++;
16
+ }
17
+ }
18
+ }
19
+ return count ;
20
+ }
21
+ public void bfs (char [][] grid , boolean [][] visited , Queue <Pair > island ){
22
+ int [] mx = {-1 , 1 , 0 , 0 };
23
+ int [] my = {0 , 0 , -1 , 1 };
24
+
25
+
26
+ while (!island .isEmpty ()){
27
+ Pair p = island .poll ();
28
+ for (int i = 0 ; i < 4 ; i ++){
29
+ int nx = mx [i ] + p .x ;
30
+ int ny = my [i ] + p .y ;
31
+
32
+ if (nx < 0 || ny < 0 || nx >= grid .length || ny >= grid [0 ].length ) continue ;
33
+ if (visited [nx ][ny ] || grid [nx ][ny ] == '0' ) continue ;
34
+
35
+ island .offer (new Pair (nx , ny ));
36
+ visited [nx ][ny ] = true ;
37
+ }
38
+
39
+ }
40
+ }
41
+
42
+ class Pair {
43
+ int x ;
44
+ int y ;
45
+ Pair (int x , int y ){
46
+ this .x = x ;
47
+ this .y = y ;
48
+ }
49
+ }
50
+ }
51
+
You can’t perform that action at this time.
0 commit comments