-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReturnToBase.java
More file actions
40 lines (33 loc) · 1.06 KB
/
Copy pathReturnToBase.java
File metadata and controls
40 lines (33 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.*;
class Solution {
public int[] solution(int n, int[][] roads, int[] sources, int destination) {
// destination 에서 각 위치까지의 최단경로
List<Integer>[] graph = new ArrayList[n+1];
for(int i = 0; i <= n; i++) {
graph[i] = new ArrayList<>();
}
for(int[] x : roads) {
graph[x[0]].add(x[1]);
graph[x[1]].add(x[0]);
}
int[] dist = new int[n+1];
Arrays.fill(dist, -1);
dist[destination] = 0;
Deque<Integer> que = new ArrayDeque<>();
que.offer(destination);
while(!que.isEmpty()) {
int current = que.poll();
for(int next : graph[current]) {
if(dist[next] == -1) {
dist[next] = dist[current] + 1;
que.offer(next);
}
}
}
int[] answer = new int[sources.length];
for (int i = 0; i < sources.length; i++) {
answer[i] = dist[sources[i]];
}
return answer;
}
}