File tree 1 file changed +54
-0
lines changed
1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ //BFS way to solve this
2
+ const bfs = ( grid , r , c ) => {
3
+ const [ ROWS , COLS ] = [ grid . length , grid [ 0 ] . length ] ;
4
+
5
+ const directions = [
6
+ [ - 1 , 0 ] ,
7
+ [ 1 , 0 ] ,
8
+ [ 0 , - 1 ] ,
9
+ [ 0 , 1 ] ,
10
+ ] ;
11
+
12
+ let queue = [ [ r , c ] ] ;
13
+
14
+ //marks as visited
15
+ grid [ r ] [ c ] = '0' ;
16
+
17
+ while ( queue . length > 0 ) {
18
+ //dequeues the first element(current)
19
+ let [ cr , cc ] = queue . shift ( ) ;
20
+
21
+ directions . forEach ( ( [ dr , dc ] ) => {
22
+ let [ nr , nc ] = [ cr + dr , cc + dc ] ;
23
+ if (
24
+ ! (
25
+ nr < 0 ||
26
+ nc < 0 ||
27
+ nr >= ROWS ||
28
+ nc >= COLS ||
29
+ grid [ nr ] [ nc ] === '0'
30
+ )
31
+ ) {
32
+ queue . push ( [ nr , nc ] ) ;
33
+ grid [ nr ] [ nc ] = '0' ;
34
+ }
35
+ } ) ;
36
+ }
37
+ } ;
38
+
39
+ function numIslands ( grid : string [ ] [ ] ) : number {
40
+ const [ ROWS , COLS ] = [ grid . length , grid [ 0 ] . length ] ;
41
+
42
+ let islands = 0 ;
43
+
44
+ for ( let i = 0 ; i < ROWS ; i ++ ) {
45
+ for ( let j = 0 ; j < COLS ; j ++ ) {
46
+ if ( grid [ i ] [ j ] === '1' ) {
47
+ bfs ( grid , i , j ) ;
48
+ islands ++ ;
49
+ }
50
+ }
51
+ }
52
+
53
+ return islands ;
54
+ }
You can’t perform that action at this time.
0 commit comments