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+ const input = require ( 'fs' )
2+ . readFileSync ( process . platform === 'linux' ? '/dev/stdin' : './input.txt' )
3+ . toString ( )
4+ . trim ( )
5+ . split ( '\n' ) ;
6+
7+ function solution ( input ) {
8+ const n = Number ( input [ 0 ] ) ;
9+ const graph = { } ;
10+
11+ for ( let i = 1 ; i <= n ; i ++ ) {
12+ const [ from , , to ] = input [ i ] . split ( ' ' ) ;
13+ if ( ! graph [ from ] ) graph [ from ] = [ ] ;
14+ graph [ from ] . push ( to ) ;
15+ }
16+
17+ const m = Number ( input [ n + 1 ] ) ;
18+ const queries = input . slice ( n + 2 ) ;
19+
20+ const results = [ ] ;
21+
22+ function dfs ( current , target , visited ) {
23+ if ( current === target ) return true ;
24+ if ( ! graph [ current ] ) return false ;
25+
26+ for ( const next of graph [ current ] ) {
27+ if ( ! visited . has ( next ) ) {
28+ visited . add ( next ) ;
29+ if ( dfs ( next , target , visited ) ) return true ;
30+ }
31+ }
32+ return false ;
33+ }
34+
35+ for ( const q of queries ) {
36+ const [ from , , to ] = q . split ( ' ' ) ;
37+ const visited = new Set ( ) ;
38+ visited . add ( from ) ;
39+ results . push ( dfs ( from , to , visited ) ? 'T' : 'F' ) ;
40+ }
41+
42+ return results . join ( '\n' ) ;
43+ }
44+
45+ console . log ( solution ( input ) ) ;
You can’t perform that action at this time.
0 commit comments