File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ function solution ( n , wires ) {
2+ const graph = Array . from ( { length : n + 1 } , ( ) => [ ] ) ;
3+
4+ for ( const [ v1 , v2 ] of wires ) {
5+ graph [ v1 ] . push ( v2 ) ;
6+ graph [ v2 ] . push ( v1 ) ;
7+ }
8+
9+ let minDifference = Number . MAX_VALUE ;
10+
11+ const dfs = ( node , visited ) => {
12+ let count = 1 ;
13+ visited [ node ] = true ;
14+
15+ for ( const neighbor of graph [ node ] ) {
16+ if ( ! visited [ neighbor ] ) {
17+ count += dfs ( neighbor , visited ) ;
18+ }
19+ }
20+
21+ return count ;
22+ } ;
23+
24+ for ( const [ v1 , v2 ] of wires ) {
25+ const visited = Array ( n + 1 ) . fill ( false ) ;
26+ visited [ v1 ] = true ;
27+ const count = dfs ( v2 , visited ) ;
28+ const difference = Math . abs ( count - ( n - count ) ) ;
29+ minDifference = Math . min ( minDifference , difference ) ;
30+ }
31+
32+ return minDifference ;
33+ }
You can’t perform that action at this time.
0 commit comments