File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.util.* ;
3+
4+ class Solution {
5+ public int solution (int n , int [][] edge ) {
6+ List<List<Integer > > graph = new ArrayList<> ();
7+
8+ for (int i = 0 ; i <= n; i++ ) {
9+ graph. add(new ArrayList<> ());
10+ }
11+
12+ for (int [] e : edge) {
13+ graph. get(e[0 ]). add(e[1 ]);
14+ graph. get(e[1 ]). add(e[0 ]);
15+ }
16+
17+ int [] dist = new int [n+ 1 ];
18+ Arrays . fill(dist, - 1 );
19+
20+ Queue<Integer > q = new LinkedList<> ();
21+ q. add(1 );
22+ dist[1 ] = 0 ;
23+
24+ while (! q. isEmpty()) {
25+ int cur = q. poll();
26+ for (int next : graph. get(cur)) {
27+ if (dist[next] == - 1 ) {
28+ dist[next] = dist[cur] + 1 ;
29+ q. add(next);
30+ }
31+ }
32+ }
33+
34+ int max = Integer . MIN_VALUE ;
35+
36+ for (int d : dist) {
37+ if (d > max) max = d;
38+ }
39+
40+ int answer = 0 ;
41+
42+ for (int d : dist) if (d == max) answer++ ;
43+
44+ return answer;
45+ }
46+ }
47+ ```
You can’t perform that action at this time.
0 commit comments