Skip to content

Commit 41acdc2

Browse files
authored
Merge pull request #795 from AlgorithmWithGod/suyeun84
[20250901] PGM / LV3 / 부대복귀 / 김수연
2 parents f30e668 + ddbc3b3 commit 41acdc2

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
```java
2+
import java.util.*;
3+
class Solution {
4+
int[] answer;
5+
int[] result;
6+
List<Integer> graph[];
7+
8+
public int[] solution(int n, int[][] roads, int[] sources, int destination) {
9+
answer = new int[n+1];
10+
result = new int[sources.length];
11+
graph = new ArrayList[n+1];
12+
Arrays.fill(answer, -1);
13+
14+
for (int i = 0; i < n+1; i++) {
15+
graph[i] = new ArrayList<>();
16+
}
17+
18+
for (int[] road : roads) {
19+
graph[road[0]].add(road[1]);
20+
graph[road[1]].add(road[0]);
21+
}
22+
23+
bfs(destination);
24+
25+
for (int i = 0; i < sources.length; i++) {
26+
result[i] = answer[sources[i]];
27+
}
28+
return result;
29+
}
30+
public void bfs(int start) {
31+
Queue<Integer> q = new ArrayDeque<>();
32+
q.add(start);
33+
answer[start] = 0;
34+
while (!q.isEmpty()) {
35+
int curr = q.poll();
36+
for (int next : graph[curr]) {
37+
if (answer[next] == -1) {
38+
answer[next] = answer[curr] + 1;
39+
q.add(next);
40+
}
41+
}
42+
}
43+
}
44+
}
45+
```

0 commit comments

Comments
 (0)