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 (
3+ process . platform === "linux"
4+ ? "/dev/stdin"
5+ : require ( "path" ) . join ( __dirname , "input.txt" ) ,
6+ "utf8"
7+ )
8+ . toString ( )
9+ . trim ( )
10+ . split ( "\n" )
11+ . map ( ( line ) => line . split ( " " ) . map ( Number ) ) ;
12+
13+ function solution ( input ) {
14+ const [ N , M , K , X ] = input [ 0 ] ;
15+ const graph = Array . from ( { length : N + 1 } , ( ) => [ ] ) ;
16+ const dist = Array ( N + 1 ) . fill ( - 1 ) ;
17+
18+ for ( let i = 1 ; i <= M ; i ++ ) {
19+ const [ a , b ] = input [ i ] ;
20+ graph [ a ] . push ( b ) ;
21+ }
22+
23+ const queue = [ X ] ;
24+ dist [ X ] = 0 ;
25+
26+ while ( queue . length > 0 ) {
27+ const current = queue . shift ( ) ;
28+ for ( const next of graph [ current ] ) {
29+ if ( dist [ next ] === - 1 ) {
30+ dist [ next ] = dist [ current ] + 1 ;
31+ queue . push ( next ) ;
32+ }
33+ }
34+ }
35+
36+ const answer = [ ] ;
37+ for ( let i = 1 ; i <= N ; i ++ ) {
38+ if ( dist [ i ] === K ) answer . push ( i ) ;
39+ }
40+
41+ if ( answer . length === 0 ) {
42+ return - 1 ;
43+ } else {
44+ return answer . sort ( ( a , b ) => a - b ) . join ( "\n" ) ;
45+ }
46+ }
47+
48+ console . log ( solution ( input ) ) ;
You can’t perform that action at this time.
0 commit comments