|
| 1 | +``` |
| 2 | +import java.util.*; |
| 3 | +
|
| 4 | +class Solution { |
| 5 | + private final int INF = Integer.MAX_VALUE - 10; |
| 6 | + private List<Integer>[] graph; |
| 7 | + private int[] dist; |
| 8 | + |
| 9 | + public int[] solution(int n, int[][] roads, int[] sources, int destination) { |
| 10 | + init(n, roads); |
| 11 | + int[] answer = new int[sources.length]; |
| 12 | + |
| 13 | + dijkstra(destination); |
| 14 | + |
| 15 | + for (int i = 0; i < answer.length; i++) { |
| 16 | + int result = dist[sources[i]]; |
| 17 | + if (result == INF) answer[i] = -1; |
| 18 | + else answer[i] = result; |
| 19 | + } |
| 20 | + |
| 21 | + return answer; |
| 22 | + } |
| 23 | + |
| 24 | + private void init(int n, int[][] roads) { |
| 25 | + graph = new List[n+1]; |
| 26 | + dist = new int[n+1]; |
| 27 | + |
| 28 | + for (int i = 0; i <= n; i++) { |
| 29 | + graph[i] = new ArrayList<>(); |
| 30 | + } |
| 31 | + |
| 32 | + for (int[] road : roads) { |
| 33 | + graph[road[0]].add(road[1]); |
| 34 | + graph[road[1]].add(road[0]); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + private void dijkstra(int start) { |
| 39 | + PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> Long.compare(o1.cost, o2.cost)); |
| 40 | + Arrays.fill(dist, INF); |
| 41 | + dist[start] = 0; |
| 42 | + pq.add(new Node(start, dist[start])); |
| 43 | + |
| 44 | + while (!pq.isEmpty()) { |
| 45 | + Node current = pq.poll(); |
| 46 | + |
| 47 | + if (current.cost > dist[current.dest]) continue; |
| 48 | + |
| 49 | + for (Integer next : graph[current.dest]) { |
| 50 | + int nCost = 1 + dist[current.dest]; |
| 51 | + |
| 52 | + if (nCost < dist[next]) { |
| 53 | + dist[next] = nCost; |
| 54 | + pq.add(new Node(next, dist[next])); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + class Node { |
| 61 | + int dest; |
| 62 | + int cost; |
| 63 | + |
| 64 | + Node (int dest, int cost) { |
| 65 | + this.dest = dest; |
| 66 | + this.cost = cost; |
| 67 | + } |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments