File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ // TC: O(n), where N = total number of cells = m * n
2
+ // SC: O(n)
3
+
4
+ function numIslands ( grid : string [ ] [ ] ) : number {
5
+ const sink = ( row : number , col : number ) => {
6
+ visited [ row ] [ col ] = true ;
7
+
8
+ const dirs = [
9
+ [ row - 1 , col ] ,
10
+ [ row + 1 , col ] ,
11
+ [ row , col - 1 ] ,
12
+ [ row , col + 1 ] ,
13
+ ] ;
14
+
15
+ for ( const dir of dirs ) {
16
+ const [ r , c ] = dir ;
17
+
18
+ if ( r >= 0 && r < grid . length && c >= 0 && c < grid [ 0 ] . length ) {
19
+ if ( ! visited [ r ] [ c ] && grid [ r ] [ c ] === "1" ) {
20
+ sink ( r , c ) ;
21
+ }
22
+ }
23
+ }
24
+ } ;
25
+
26
+ let count = 0 ;
27
+ const visited : boolean [ ] [ ] = Array . from ( { length : grid . length } , ( ) =>
28
+ Array ( grid [ 0 ] . length ) . fill ( false )
29
+ ) ;
30
+
31
+ for ( let i = 0 ; i < grid . length ; i ++ ) {
32
+ for ( let j = 0 ; j < grid [ 0 ] . length ; j ++ ) {
33
+ if ( ! visited [ i ] [ j ] && grid [ i ] [ j ] === "1" ) {
34
+ count ++ ;
35
+ sink ( i , j ) ; // // Sink all connected neighboring land cells
36
+ }
37
+ }
38
+ }
39
+
40
+ return count ;
41
+ }
You can’t perform that action at this time.
0 commit comments