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 , M , K , X ] = input [ 0 ] ;
10+ const graph = Array . from ( { length : N + 1 } , ( ) => [ ] ) ;
11+ const visited = Array . from ( { length : N + 1 } , ( ) => false ) ;
12+ const info = input . slice ( 1 ) ;
13+
14+ for ( let i = 0 ; i < M ; i ++ ) {
15+ const [ a , b ] = info [ i ] ;
16+ graph [ a ] . push ( b ) ;
17+ }
18+ const queue = [ ] ;
19+ const result = [ ] ;
20+ queue . push ( [ X , 0 ] ) ;
21+ visited [ X ] = true ;
22+ while ( queue . length ) {
23+ const [ node , cnt ] = queue . shift ( ) ;
24+ if ( cnt === K ) {
25+ result . push ( node ) ;
26+ continue ;
27+ }
28+ for ( const next of graph [ node ] ) {
29+ if ( ! visited [ next ] ) {
30+ visited [ next ] = true ;
31+ queue . push ( [ next , cnt + 1 ] ) ;
32+ }
33+ }
34+ }
35+ result . sort ( ( a , b ) => a - b ) ;
36+ if ( result . length === 0 ) {
37+ return - 1 ;
38+ }
39+ return result . join ( '\n' ) ;
40+ }
41+
42+ console . log ( solution ( input ) ) ;
You can’t perform that action at this time.
0 commit comments