Skip to content

Commit 1a1c78f

Browse files
authored
Merge pull request #1451 from AlgorithmWithGod/lkhyun
[20251119] PGM / Lv3 / 가장 먼 노드 / 이강현
2 parents 61d0aee + 7c1f46b commit 1a1c78f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
```

0 commit comments

Comments
 (0)