File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @param {character[][] } grid
3+ * @return {number }
4+ */
5+ var numIslands = function ( grid ) {
6+ if ( ! grid . length ) return 0 ;
7+
8+ const rows = grid . length ;
9+ const cols = grid [ 0 ] . length ;
10+ const visit = new Set ( ) ;
11+ let islands = 0 ;
12+
13+ const bfs = ( r , c ) => {
14+ const queue = [ ] ;
15+ queue . push ( [ r , c ] ) ;
16+ visit . add ( `${ r } ,${ c } ` ) ;
17+
18+ while ( queue . length ) {
19+ const [ row , col ] = queue . shift ( ) ;
20+ const directions = [
21+ [ 1 , 0 ] ,
22+ [ - 1 , 0 ] ,
23+ [ 0 , 1 ] ,
24+ [ 0 , - 1 ] ,
25+ ] ;
26+
27+ for ( const [ dr , dc ] of directions ) {
28+ const newRow = row + dr ;
29+ const newCol = col + dc ;
30+
31+ if (
32+ newRow >= 0 &&
33+ newRow < rows &&
34+ newCol >= 0 &&
35+ newCol < cols &&
36+ grid [ newRow ] [ newCol ] === '1' &&
37+ ! visit . has ( `${ newRow } ,${ newCol } ` )
38+ ) {
39+ queue . push ( [ newRow , newCol ] ) ;
40+ visit . add ( `${ newRow } ,${ newCol } ` ) ;
41+ }
42+ }
43+ }
44+ } ;
45+
46+ for ( let r = 0 ; r < rows ; r ++ ) {
47+ for ( let c = 0 ; c < cols ; c ++ ) {
48+ if ( grid [ r ] [ c ] === '1' && ! visit . has ( `${ r } ,${ c } ` ) ) {
49+ bfs ( r , c ) ;
50+ islands += 1 ;
51+ }
52+ }
53+ }
54+
55+ return islands ;
56+ } ;
You can’t perform that action at this time.
0 commit comments