Given times
, a list of travel times as directed edges times[i] = (u, v, w)
, where u
is the source node, v
is the target node, and w
is the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain node K
. How long will it take for all nodes to receive the signal? If it is impossible, return -1
.
Example 1:
Input: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2
Output: 2
思路:network delay time 跟 Cheapest Flights Within K Stops 一模一样,都是dijkstra算法;其实这个题是在算arrive最后一个node的最大时间,其实也是最小的时间,因为arrive每个点,我们每次都是用最小的time去算的,只是最后结果,我们要最后arrive那个点的时间。注意,这里需要判断一下graph.get(node.id)是否为空;这个很重要;
class Solution {
public class Node {
int id;
int time;
public Node(int id, int time) {
this.id = id;
this.time = time;
}
}
public int networkDelayTime(int[][] times, int n, int k) {
HashMap<Integer, HashMap<Integer, Integer>> graph = new HashMap<>();
for(int[] time: times) {
int u = time[0];
int v = time[1];
int w = time[2];
graph.putIfAbsent(u, new HashMap<>());
graph.get(u).put(v, w);
}
PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) ->(a.time - b.time));
pq.offer(new Node(k, 0));
int maxtime = 0;
HashSet<Integer> visited = new HashSet<>();
while(!pq.isEmpty()) {
Node node = pq.poll();
if(visited.contains(node.id)) {
continue;
}
visited.add(node.id);
maxtime = Math.max(maxtime, node.time);
if(graph.get(node.id) != null) {
for(Integer neighbor: graph.get(node.id).keySet()) {
pq.offer(new Node(neighbor, node.time + graph.get(node.id).get(neighbor)));
}
}
}
return visited.size() == n ? maxtime : -1;
}
}