|
| 1 | +import java.util.Arrays; |
| 2 | +import java.util.HashMap; |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.PriorityQueue; |
| 7 | + |
1 | 8 | /*
|
2 | 9 | * @lc app=leetcode.cn id=743 lang=java
|
3 | 10 | *
|
|
6 | 13 |
|
7 | 14 | // @lc code=start
|
8 | 15 | class Solution {
|
| 16 | + public static List<int[]>[] graph; |
| 17 | + |
9 | 18 | public int networkDelayTime(int[][] times, int n, int k) {
|
| 19 | + buildGraph(times, n); |
| 20 | + int[] distToTarget = new int[n + 1]; |
| 21 | + Arrays.fill(distToTarget, Integer.MAX_VALUE); |
| 22 | + distToTarget[k] = 0; |
| 23 | + |
| 24 | + PriorityQueue<State> pq = new PriorityQueue<State>((a, b) -> a.distFromStart - b.distFromStart); |
| 25 | + pq.add(new State(k, 0)); |
| 26 | + |
| 27 | + while (!pq.isEmpty()) { |
| 28 | + State state = pq.poll(); |
| 29 | + if (state.distFromStart > distToTarget[state.id]) |
| 30 | + continue; |
| 31 | + List<int[]> targets = graph[state.id]; |
| 32 | + for (int[] target : targets) { |
| 33 | + int t = target[0]; |
| 34 | + int w = target[1]; |
| 35 | + int distFromStart = w + state.distFromStart; |
| 36 | + if (distToTarget[t] > distFromStart) { |
| 37 | + distToTarget[t] = distFromStart; |
| 38 | + pq.offer(new State(t, distFromStart)); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + int max = 0; |
| 43 | + for (int i = 1; i < distToTarget.length; i++) { |
| 44 | + max = Math.max(max, distToTarget[i]); |
| 45 | + } |
| 46 | + |
| 47 | + return max == Integer.MAX_VALUE ? -1 : max; |
| 48 | + |
| 49 | + } |
10 | 50 |
|
| 51 | + private static void buildGraph(int[][] times, int n) { |
| 52 | + List<int[]>[] list = new LinkedList[n + 1]; |
| 53 | + for (int i = 0; i < list.length; i++) { |
| 54 | + list[i] = new LinkedList<>(); |
| 55 | + } |
| 56 | + for (int[] g : times) { |
| 57 | + int from = g[0]; |
| 58 | + int to = g[1]; |
| 59 | + int weight = g[2]; |
| 60 | + list[from].add(new int[] { to, weight }); |
| 61 | + } |
| 62 | + graph = list; |
11 | 63 | }
|
12 | 64 | }
|
13 |
| -// @lc code=end |
14 | 65 |
|
| 66 | +class State { |
| 67 | + public int id; |
| 68 | + public int distFromStart; |
| 69 | + |
| 70 | + public State(int id, int distFromStart) { |
| 71 | + this.id = id; |
| 72 | + this.distFromStart = distFromStart; |
| 73 | + } |
| 74 | +} |
| 75 | +// @lc code=end |
0 commit comments