File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ function solution ( maps ) {
2+ const n = maps . length ;
3+ const m = maps [ 0 ] . length ;
4+ const directions = [
5+ [ 1 , 0 ] ,
6+ [ - 1 , 0 ] ,
7+ [ 0 , 1 ] ,
8+ [ 0 , - 1 ] ,
9+ ] ;
10+ const queue = [ [ 0 , 0 ] ] ;
11+ const visited = Array . from ( { length : n } , ( ) => Array ( m ) . fill ( false ) ) ;
12+ visited [ 0 ] [ 0 ] = true ;
13+ let count = 1 ;
14+
15+ while ( queue . length > 0 ) {
16+ const size = queue . length ;
17+ for ( let i = 0 ; i < size ; i ++ ) {
18+ const [ x , y ] = queue . shift ( ) ;
19+
20+ if ( x === n - 1 && y === m - 1 ) {
21+ return count ;
22+ }
23+
24+ for ( const [ dx , dy ] of directions ) {
25+ const nx = x + dx ;
26+ const ny = y + dy ;
27+
28+ if (
29+ nx >= 0 &&
30+ ny >= 0 &&
31+ nx < n &&
32+ ny < m &&
33+ maps [ nx ] [ ny ] === 1 &&
34+ ! visited [ nx ] [ ny ]
35+ ) {
36+ visited [ nx ] [ ny ] = true ;
37+ queue . push ( [ nx , ny ] ) ;
38+ }
39+ }
40+ }
41+ count ++ ;
42+ }
43+
44+ return - 1 ;
45+ }
You can’t perform that action at this time.
0 commit comments