1
+ namespace LeetCodeSolutions . Graph
2
+ {
3
+ public class NumberOfIslands
4
+ {
5
+ public int NumIslands ( char [ ] [ ] grid )
6
+ {
7
+ int islandCount = 0 ;
8
+ int rows = grid . Length ;
9
+ int cols = grid [ 0 ] . Length ;
10
+
11
+ // Iterate through each cell in the grid
12
+ for ( int row = 0 ; row < rows ; row ++ )
13
+ {
14
+ for ( int col = 0 ; col < cols ; col ++ )
15
+ {
16
+ // When we find a land cell ('1'), explore the entire island
17
+ if ( grid [ row ] [ col ] == '1' )
18
+ {
19
+ islandCount ++ ;
20
+ ExploreIsland ( grid , row , col ) ;
21
+ }
22
+ }
23
+ }
24
+
25
+ return islandCount ;
26
+ }
27
+
28
+ private void ExploreIsland ( char [ ] [ ] grid , int row , int col )
29
+ {
30
+ int rows = grid . Length ;
31
+ int cols = grid [ 0 ] . Length ;
32
+
33
+ // Check boundary conditions and if current cell is land
34
+ if ( row < 0 || col < 0 || row >= rows || col >= cols || grid [ row ] [ col ] == '0' )
35
+ {
36
+ return ;
37
+ }
38
+
39
+ // Mark current cell as visited
40
+ grid [ row ] [ col ] = '0' ;
41
+
42
+ // Explore in all four directions (up, right, down, left)
43
+ ExploreIsland ( grid , row + 1 , col ) ; // Down
44
+ ExploreIsland ( grid , row - 1 , col ) ; // Up
45
+ ExploreIsland ( grid , row , col + 1 ) ; // Right
46
+ ExploreIsland ( grid , row , col - 1 ) ; // Left
47
+ }
48
+
49
+ [ Test ( Description = "https://leetcode.com/problems/number-of-islands/" ) ]
50
+ [ Category ( "Medium" ) ]
51
+ [ Category ( "LeetCode" ) ]
52
+ [ Category ( "Number of Islands" ) ]
53
+ [ TestCaseSource ( nameof ( Input ) ) ]
54
+ [ Category ( "Graph" ) ]
55
+ [ Category ( "TopInterview" ) ]
56
+ public void Test1 ( ( int Output , char [ ] [ ] Input ) item )
57
+ {
58
+ var response = this . NumIslands ( item . Input ) ;
59
+ Assert . That ( response , Is . EqualTo ( item . Output ) ) ;
60
+ }
61
+
62
+ public static IEnumerable < ( int Output , char [ ] [ ] Input ) > Input =>
63
+ new List < ( int Output , char [ ] [ ] Input ) > ( )
64
+ {
65
+ ( 1 , [
66
+ [ '1' , '1' , '1' , '1' , '0' ] ,
67
+ [ '1' , '1' , '0' , '1' , '0' ] ,
68
+ [ '1' , '1' , '0' , '0' , '0' ] ,
69
+ [ '0' , '0' , '0' , '0' , '0' ]
70
+ ] )
71
+ } ;
72
+ }
73
+ }
0 commit comments