|
1 | 1 | class Solution {
|
2 |
| - public int networkDelayTime(int[][] times, int N, int K) { |
3 |
| - Map<Integer, List<Connection>> map = new HashMap<>(); |
| 2 | + public int networkDelayTime(int[][] times, int n, int k) { |
| 3 | + // Mapping from node to all outgoing edges alongside weight of each edge |
| 4 | + Map<Integer, List<int[]>> map = new HashMap<>(); |
4 | 5 | for (int[] time : times) {
|
5 |
| - map.computeIfAbsent(time[0], k -> new ArrayList<>()).add(new Connection(time[1], time[2])); |
| 6 | + map.computeIfAbsent(time[0], j -> new ArrayList<>()).add(new int[] {time[1], time[2]}); |
6 | 7 | }
|
7 |
| - Map<Integer, Integer> dist = new HashMap<>(); |
8 |
| - for (int node = 1; node <= N; node++) { |
9 |
| - dist.put(node, Integer.MAX_VALUE); |
10 |
| - } |
11 |
| - dist.put(K, 0); |
12 |
| - boolean[] seen = new boolean[N + 1]; |
13 |
| - while (true) { |
14 |
| - int candNode = -1; |
15 |
| - int candDist = Integer.MAX_VALUE; |
16 |
| - for (int i = 1; i <= N; ++i) { |
17 |
| - if (!seen[i] && dist.get(i) < candDist) { |
18 |
| - candDist = dist.get(i); |
19 |
| - candNode = i; |
20 |
| - } |
21 |
| - } |
22 |
| - if (candNode < 0) { |
23 |
| - break; |
24 |
| - } |
25 |
| - seen[candNode] = true; |
26 |
| - for (Connection con: map.getOrDefault(candNode, new ArrayList<>())) { |
27 |
| - dist.put(con.val, Math.min(dist.get(con.val), dist.get(candNode) + con.time)); |
| 8 | + // Min heap in order of edge weight |
| 9 | + PriorityQueue<int[]> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(o -> o[0])); |
| 10 | + priorityQueue.add(new int[] {0, k}); |
| 11 | + Set<Integer> visited = new HashSet<>(); |
| 12 | + int totalTime = 0; |
| 13 | + while (!priorityQueue.isEmpty()) { |
| 14 | + int[] removed = priorityQueue.poll(); |
| 15 | + int currNode = removed[1]; |
| 16 | + int edgeWeight = removed[0]; |
| 17 | + if (visited.contains(currNode)) { |
| 18 | + continue; |
28 | 19 | }
|
29 |
| - } |
30 |
| - int ans = 0; |
31 |
| - for (int cand: dist.values()) { |
32 |
| - if (cand == Integer.MAX_VALUE) { |
33 |
| - return -1; |
| 20 | + visited.add(currNode); |
| 21 | + totalTime = Math.max(totalTime, edgeWeight); |
| 22 | + for (int[] neighbor : map.getOrDefault(removed[1], new ArrayList<>())) { |
| 23 | + int neighborNode = neighbor[0]; |
| 24 | + int neighborEdgeWeight = neighbor[1]; |
| 25 | + if (!visited.contains(neighborNode)) { |
| 26 | + priorityQueue.add(new int[] {neighborEdgeWeight + edgeWeight, neighborNode}); |
| 27 | + } |
34 | 28 | }
|
35 |
| - ans = Math.max(ans, cand); |
36 | 29 | }
|
37 |
| - return ans; |
38 |
| - } |
39 |
| -} |
40 |
| - |
41 |
| -class Connection { |
42 |
| - int val; |
43 |
| - int time; |
44 |
| - |
45 |
| - public Connection(int val, int time) { |
46 |
| - this.val = val; |
47 |
| - this.time = time; |
| 30 | + return visited.size() == n ? totalTime : -1; |
48 | 31 | }
|
49 | 32 | }
|
0 commit comments