# LeetCode 743. Network Delay Time

There are `N` network nodes, labelled `1` to `N`.

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`

Note:

1. `N` will be in the range `[1, 100]`.
2. `K` will be in the range `[1, N]`.
3. The length of `times` will be in the range `[1, 6000]`.
4. All edges `times[i] = (u, v, w)` will have `1 <= u, v <= N` and `0 <= w <= 100`.

Construct a graph. Then use the shortest time to traverse to the point.

Have a minHeap based on the time spent to get to the point. With the graph and current point, find all the next points and calculate the time to get to that point, current.time + time from current to next point, put it to minHeap.

Thus, we could always get to a point with shortest time.

Note: Update visited set when poll out of minHeap but not before adding to the heap. Otherwise, if it takes very long time to next point and  add the next point to visited, later if there is shorter path to that point, it can‘t be added to minHeap.

So update visited set after polling out of minHeap and update res if it is not visited before.

Time Complexity: O(E+VlogV). It takes O(E) time to construct graph. O(VlogV) time to traverse all the points.

Space: O(E+V). O(E) for graph, O(V) for minHeap and Set.

AC Java:

``` 1 class Solution {
2     public int networkDelayTime(int[][] times, int N, int K) {
3         Map<Integer, List<int []>> graph = new HashMap<>();
4         for(int [] edge : times){
5             graph.putIfAbsent(edge, new ArrayList<int []>());
7         }
8
9         int res = 0;
10
11         PriorityQueue<int []> minHeap = new PriorityQueue<int []>((a,b) -> a-b);
13         Set<Integer> visited = new HashSet<Integer>();
14         int count = 0;
15
16         while(!minHeap.isEmpty()){
17             int[] cur = minHeap.poll();
18             if(visited.contains(cur)){
19                 continue;
20             }
21
23             count++;
24             res = cur;
25             if(graph.containsKey(cur)){
26                 for(int [] next : graph.get(cur)){
28                 }
29             }
30         }
31
32         return count == N ? res : -1;
33     }
34 }```

### 精彩评论 换一张 