File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @description
3
+ * brainstorming:
4
+ * hash table + two pointer
5
+ *
6
+ * n = length of grid
7
+ * k = length of grid[index]
8
+ * time complexity: O(n * k)
9
+ * space complexity: O(n * k)
10
+ */
11
+ var numIslands = function ( grid ) {
12
+ let answer = 0 ;
13
+ const visited = Array . from ( { length : grid . length } , ( _ , i ) =>
14
+ Array . from ( { length : grid [ i ] . length } , ( ) => false )
15
+ ) ;
16
+
17
+ const dfs = ( r , c ) => {
18
+ const dr = [ 0 , 1 , 0 , - 1 ] ;
19
+ const dc = [ 1 , 0 , - 1 , 0 ] ;
20
+
21
+ for ( let i = 0 ; i < 4 ; i ++ ) {
22
+ const nextR = r + dr [ i ] ;
23
+ const nextC = c + dc [ i ] ;
24
+
25
+ if (
26
+ nextR >= 0 &&
27
+ nextR < grid . length &&
28
+ nextC >= 0 &&
29
+ nextC < grid [ r ] . length &&
30
+ grid [ nextR ] [ nextC ] == 1 &&
31
+ ! visited [ nextR ] [ nextC ]
32
+ ) {
33
+ visited [ nextR ] [ nextC ] = true ;
34
+ dfs ( nextR , nextC ) ;
35
+ }
36
+ }
37
+ } ;
38
+
39
+ for ( let row = 0 ; row < grid . length ; row ++ ) {
40
+ for ( let column = 0 ; column < grid [ row ] . length ; column ++ ) {
41
+ if ( grid [ row ] [ column ] == 1 && ! visited [ row ] [ column ] ) {
42
+ visited [ row ] [ column ] = true ;
43
+ answer ++ ;
44
+ dfs ( row , column ) ;
45
+ }
46
+ }
47
+ }
48
+ return answer ;
49
+ } ;
You can’t perform that action at this time.
0 commit comments