File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ let input = require ( 'fs' ) . readFileSync ( 'dev/stdin' ) . toString ( ) . trim ( ) . split ( '\n' ) ;
2
+
3
+ const [ n , m ] = input . shift ( ) . split ( " " ) ;
4
+ let graph = input . map ( arr => arr . split ( "" ) . map ( x => + x ) ) ;
5
+
6
+ const BFS = ( n , m , arr ) => {
7
+ const dx = [ - 1 , 0 , 1 , 0 ] ;
8
+ const dy = [ 0 , 1 , 0 , - 1 ] ;
9
+
10
+ let queue = [ ] ;
11
+ queue . push ( { x : 0 , y : 0 } ) ;
12
+
13
+ while ( queue . length ) {
14
+ const target = queue . shift ( ) ;
15
+ for ( let i = 0 ; i < 4 ; i ++ ) {
16
+ const nextX = target . x + dx [ i ] ;
17
+ const nextY = target . y + dy [ i ] ;
18
+
19
+ if ( nextX < 0 || nextX >= n || nextY < 0 || nextY >= m ) {
20
+ continue ;
21
+ }
22
+
23
+ if ( arr [ nextX ] [ nextY ] !== 1 ) {
24
+ continue ;
25
+ }
26
+
27
+ arr [ nextX ] [ nextY ] = arr [ target . x ] [ target . y ] + 1 ;
28
+ queue . push ( { x : nextX , y : nextY } ) ;
29
+ }
30
+ }
31
+ return arr [ n - 1 ] [ m - 1 ] ;
32
+ }
33
+
34
+ const answer = BFS ( n , m , graph )
35
+ console . log ( answer )
You can’t perform that action at this time.
0 commit comments