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