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 = input [ 0 ] [ 0 ] ;
10+ const M = input [ 1 ] [ 0 ] ;
11+ const computerList = input . slice ( 2 ) ;
12+
13+ const graph = Array . from ( { length : N + 1 } , ( ) => [ ] ) ;
14+ const visited = Array . from ( { length : N + 1 } ) . fill ( false ) ;
15+
16+ for ( let [ c1 , c2 ] of computerList ) {
17+ graph [ c1 ] . push ( c2 ) ;
18+ graph [ c2 ] . push ( c1 ) ;
19+ }
20+ let count = 0 ;
21+
22+ function dfs ( node ) {
23+ count ++ ;
24+ visited [ node ] = true ;
25+ const list = graph [ node ] ;
26+ for ( let i = 0 ; i < list . length ; i ++ ) {
27+ if ( ! visited [ list [ i ] ] ) dfs ( list [ i ] ) ;
28+ }
29+ }
30+ dfs ( 1 ) ;
31+ return count - 1 ;
32+ }
33+
34+ console . log ( solution ( input ) ) ;
You can’t perform that action at this time.
0 commit comments