File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ var numIslands = function ( grid ) {
2
+ // Declare row and column length
3
+ const m = grid . length ,
4
+ n = grid [ 0 ] . length ;
5
+ let numIslands = 0 ;
6
+
7
+ // Available directions for depth-first search
8
+ const dir = [
9
+ [ 0 , 1 ] ,
10
+ [ 1 , 0 ] ,
11
+ [ 0 , - 1 ] ,
12
+ [ - 1 , 0 ] ,
13
+ ] ;
14
+
15
+ // Function to depth-first search inside of grid
16
+ const dfs = ( i , j ) => {
17
+ grid [ i ] [ j ] = "2" ;
18
+
19
+ let x , y ;
20
+ for ( d of dir ) {
21
+ x = i + d [ 0 ] ;
22
+ y = j + d [ 1 ] ;
23
+ if ( x >= 0 && x < m && y >= 0 && y < n && grid [ x ] [ y ] === "1" ) {
24
+ dfs ( x , y ) ;
25
+ }
26
+ }
27
+ return ;
28
+ } ;
29
+
30
+ for ( let i = 0 ; i < m ; i ++ ) {
31
+ for ( let j = 0 ; j < n ; j ++ ) {
32
+ if ( grid [ i ] [ j ] === "1" ) {
33
+ dfs ( i , j ) ;
34
+ numIslands ++ ;
35
+ }
36
+ }
37
+ }
38
+ return numIslands ;
39
+ } ;
40
+
41
+ // TC: O(m*n)
42
+ // SC: O(m*n)
You can’t perform that action at this time.
0 commit comments