@@ -10,24 +10,53 @@ const input = fs
1010function solution ( input ) {
1111 const [ N , M ] = input [ 0 ] ;
1212 const relation = input . slice ( 1 ) ;
13- const graph = Array . from ( { length : N + 1 } ) . map ( ( _ ) =>
14- Array . from ( { length : 0 } )
15- ) ;
13+ const graph = Array . from ( { length : N + 1 } , ( ) => [ ] ) ;
1614
1715 for ( const [ f1 , f2 ] of relation ) {
1816 graph [ f1 ] . push ( f2 ) ;
1917 graph [ f2 ] . push ( f1 ) ;
2018 }
2119
22- function dfs ( start , target ) { }
20+ function bfs ( start , target ) {
21+ const queue = [ [ start , 0 ] ] ;
22+ const visited = Array ( N + 1 ) . fill ( false ) ;
23+ visited [ start ] = true ;
24+
25+ while ( queue . length > 0 ) {
26+ const [ current , depth ] = queue . shift ( ) ;
27+
28+ if ( current === target ) return depth ;
29+
30+ for ( let nearNode of graph [ current ] ) {
31+ if ( ! visited [ nearNode ] ) {
32+ visited [ nearNode ] = true ;
33+ queue . push ( [ nearNode , depth + 1 ] ) ;
34+ }
35+ }
36+ }
37+ return Infinity ;
38+ }
39+
40+ let minKevinBacon = Infinity ;
41+ let minUser = - 1 ;
2342
2443 for ( let i = 1 ; i <= N ; i ++ ) {
25- const temp = [ ] ;
44+ let kevinBacon = 0 ;
2645 for ( let j = 1 ; j <= N ; j ++ ) {
27- if ( graph [ i ] . includes ( j ) ) temp . push ( 1 ) ;
28- else dfs ( i , j ) ;
46+ if ( i !== j ) {
47+ kevinBacon += bfs ( i , j ) ;
48+ }
49+ }
50+
51+ if ( kevinBacon < minKevinBacon ) {
52+ minKevinBacon = kevinBacon ;
53+ minUser = i ;
54+ } else if ( kevinBacon === minKevinBacon ) {
55+ minUser = Math . min ( minUser , i ) ;
2956 }
3057 }
58+
59+ console . log ( minUser ) ;
3160}
3261
33- console . log ( solution ( input ) ) ;
62+ solution ( input ) ;
0 commit comments