#Problem

#⭐️⭐️⭐️⭐️

从一个source出发send signal, 要多少时间所有其他结点都接收到.

#Solution

Single source shortest path problem. 耗时最长的shortest path就是所要求的时间.

Dijkstra搞定.

#Note

虽然IndexHeap更好,但是如果嫌麻烦的话用Java自带的PriorityQueue, 先remove在offer可以实现decreaseKey的效果.

#Code

思路很简单,代码很难写.

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
private class Node implements Comparable<Node> {
int val;
int weight;
Node(final int val, final int weight) {
this.val = val;
this.weight = weight;
}
@Override
public int compareTo(Node other) {
return this.weight - other.weight;
}
@Override
public int hashCode() {
return val;
}
@Override
public boolean equals(Object other) {
final Node o = (Node) other;
return o.val == this.val;
}
}
public int networkDelayTime(int[][] times, int N, int K) {
final Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
final Map<Integer, Integer> dist = new HashMap<>();
for (int i = 1; i <= N; i++) {
graph.put(i, new HashMap<>());
dist.put(i, Integer.MAX_VALUE);
}
for (final int[] time : times) {
graph.get(time[0]).put(time[1], time[2]);
}
final PriorityQueue<Node> minHeap = new PriorityQueue<>();
dist.put(K, 0);
minHeap.add(new Node(K, 0));
while (!minHeap.isEmpty()) {
final Node curr = minHeap.poll();
for (final int adj : graph.get(curr.val).keySet()) {
relax(curr.val, adj, graph, dist, minHeap);
}
}
int res = 0;
for (final int v : dist.keySet()) {
if (dist.get(v) == Integer.MAX_VALUE) return -1;
else res = Math.max(res, dist.get(v));
}
return res;
}
private void relax(final int v, final int w, final Map<Integer, Map<Integer, Integer>> graph, final Map<Integer, Integer> dist, final PriorityQueue<Node> minHeap) {
final int updatedDist = dist.get(v) + graph.get(v).get(w);
if (updatedDist < dist.get(w)) {
dist.put(w, updatedDist);
Node node = new Node(w, updatedDist);
if (minHeap.contains(node)) {
minHeap.remove(node);
}
minHeap.add(node);
}
}
}

Comments