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+ function solution ( n , edge ) {
2+ const map = Array ( n + 1 )
3+ . fill ( )
4+ . map ( ( ) => [ ] ) ;
5+ for ( let i = 0 ; i < edge . length ; i ++ ) {
6+ let a = edge [ i ] [ 0 ] ;
7+ let b = edge [ i ] [ 1 ] ;
8+ map [ a ] . push ( b ) ;
9+ map [ b ] . push ( a ) ;
10+ }
11+
12+ const visited = Array ( n + 1 ) . fill ( 0 ) ;
13+ const q = [ ] ;
14+ q . push ( 1 ) ;
15+ visited [ 1 ] = 1 ;
16+
17+ while ( q . length > 0 ) {
18+ const now = q . shift ( ) ;
19+ for ( let i = 0 ; i < map [ now ] . length ; i ++ ) {
20+ let next = map [ now ] [ i ] ;
21+ if ( visited [ next ] === 0 ) {
22+ visited [ next ] = visited [ now ] + 1 ;
23+ q . push ( next ) ;
24+ }
25+ }
26+ }
27+
28+ let max = 0 ;
29+ for ( let i = 0 ; i < visited . length ; i ++ ) {
30+ if ( visited [ i ] > max ) {
31+ max = visited [ i ] ;
32+ }
33+ }
34+
35+ let answer = 0 ;
36+ for ( let i = 0 ; i < visited . length ; i ++ ) {
37+ if ( visited [ i ] === max ) {
38+ answer ++ ;
39+ }
40+ }
41+
42+ return answer ;
43+ }
44+
45+ console . log (
46+ solution ( [
47+ [ 3 , 6 ] ,
48+ [ 4 , 3 ] ,
49+ [ 3 , 2 ] ,
50+ [ 1 , 3 ] ,
51+ [ 1 , 2 ] ,
52+ [ 2 , 4 ] ,
53+ [ 5 , 2 ] ,
54+ ] )
55+ ) ;
You can’t perform that action at this time.
0 commit comments