File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const input = require ( 'fs' )
2+ . readFileSync ( process . platform === 'linux' ? '/dev/stdin' : './input.txt' )
3+ . toString ( )
4+ . trim ( )
5+ . split ( '\n' )
6+ . map ( ( el ) => el . split ( ' ' ) . map ( Number ) ) ;
7+
8+ function solution ( input ) {
9+ const [ N , K ] = input [ 0 ] ;
10+
11+ const visited = Array ( 100001 ) . fill ( false ) ;
12+
13+ if ( N >= K ) {
14+ return N - K ;
15+ }
16+
17+ const queue = [ [ N , 0 ] ] ;
18+ visited [ N ] = true ;
19+
20+ while ( queue . length ) {
21+ const [ X , time ] = queue . shift ( ) ;
22+
23+ if ( X === K ) return time ;
24+
25+ if ( X * 2 <= 100000 && ! visited [ X * 2 ] ) {
26+ visited [ X * 2 ] = true ;
27+ queue . push ( [ X * 2 , time ] ) ;
28+ }
29+ if ( X - 1 >= 0 && ! visited [ X - 1 ] ) {
30+ visited [ X - 1 ] = true ;
31+ queue . push ( [ X - 1 , time + 1 ] ) ;
32+ }
33+ if ( X + 1 <= 100000 && ! visited [ X + 1 ] ) {
34+ visited [ X + 1 ] = true ;
35+ queue . push ( [ X + 1 , time + 1 ] ) ;
36+ }
37+ }
38+ }
39+
40+ console . log ( solution ( input ) ) ;
You can’t perform that action at this time.
0 commit comments