1
+ // recursion with dfs, easy solution but not typical for these bfs problem
2
+ public class Solution {
3
+ private int m , n ;
4
+ public int NumIslands ( char [ , ] grid ) {
5
+ m = grid . GetLength ( 0 ) ;
6
+ n = grid . GetLength ( 1 ) ;
7
+ if ( m == 0 || n == 0 ) return 0 ;
8
+ int count = 0 ;
9
+ for ( int i = 0 ; i < m ; i ++ ) {
10
+ for ( int j = 0 ; j < n ; j ++ ) {
11
+ if ( grid [ i , j ] == '1' ) {
12
+ count ++ ;
13
+ DfsFill ( grid , i , j ) ;
14
+ }
15
+ }
16
+ }
17
+ return count ;
18
+ }
19
+ private void DfsFill ( char [ , ] grid , int i , int j ) {
20
+ // fill the point with label '1' and inside range
21
+ if ( i >= 0 && i < m && j >= 0 && j < n && grid [ i , j ] == '1' ) {
22
+ grid [ i , j ] = '0' ;
23
+ DfsFill ( grid , i + 1 , j ) ;
24
+ DfsFill ( grid , i - 1 , j ) ;
25
+ DfsFill ( grid , i , j + 1 ) ;
26
+ DfsFill ( grid , i , j - 1 ) ;
27
+ }
28
+ }
29
+ }
30
+
31
+ // BFS, recursion
32
+ public class Solution {
33
+ private int m , n ;
34
+ public int NumIslands ( char [ , ] grid ) {
35
+ m = grid . GetLength ( 0 ) ;
36
+ n = grid . GetLength ( 1 ) ;
37
+ if ( m == 0 || n == 0 ) return 0 ;
38
+ int count = 0 ;
39
+ for ( int i = 0 ; i < m ; i ++ ) {
40
+ for ( int j = 0 ; j < n ; j ++ ) {
41
+ if ( grid [ i , j ] == '1' ) {
42
+ count ++ ;
43
+ BfsFill ( grid , i , j ) ;
44
+ }
45
+ }
46
+ }
47
+ return count ;
48
+ }
49
+ class Point {
50
+ public int x , y ;
51
+ public Point ( int x , int y ) {
52
+ this . x = x ;
53
+ this . y = y ;
54
+ }
55
+ }
56
+ private void BfsFill ( char [ , ] grid , int x , int y ) {
57
+ int [ ] deltaX = { 1 , - 1 , 0 , 0 } ;
58
+ int [ ] deltaY = { 0 , 0 , 1 , - 1 } ;
59
+
60
+ Queue < Point > q = new Queue < Point > ( ) ;
61
+ q . Enqueue ( new Point ( x , y ) ) ;
62
+ grid [ x , y ] = '0' ;
63
+ while ( q . Count > 0 ) {
64
+ Point point1 = q . Dequeue ( ) ;
65
+ for ( int i = 0 ; i < 4 ; i ++ ) {
66
+ Point adj = new Point (
67
+ point1 . x + deltaX [ i ] ,
68
+ point1 . y + deltaY [ i ]
69
+ ) ;
70
+ if ( adj . x >= 0 && adj . x < m
71
+ && adj . y >= 0 && adj . y < n
72
+ && grid [ adj . x , adj . y ] == '1' ) {
73
+ grid [ adj . x , adj . y ] = '0' ;
74
+ q . Enqueue ( adj ) ;
75
+ }
76
+ }
77
+ }
78
+ }
79
+ }
0 commit comments