Network Delay Time
Find how long a signal sent from one node takes to reach every node of a network, or -1 if some node never gets it.
A network has nntimes[i] = [u, v, w]uvwk
Example 1
Output: 2
Example 2
Output: 1
Example 3
Output: -1
Explanation: the only link leaves node 1, so a signal from node 2 cannot reach it.
The Idea
Imagine each node as a person, and each link as a one-way phone line that takes a fixed time to pass a message along. The moment a person hears the message, they pass it on along every line that leaves them. How long until the last person has heard it?
Look at the picture below, which draws Example 1. Each circle is a node, and each arrow is one entry of times[2,1,1]
Node 2, labelled "start: k = 2", has the signal at time 0. Both of its arrows take time 1, so nodes 1 and 3 hear it at time 1. Node 3 passes it on to node 4, which hears it at 1 + 1 = 2. Node 4, labelled "hears it at 2, the last one", is the last to hear, so the answer is 2.
In Example 1 each node can be reached in only one way. What happens when there are two ways? Take three nodes with links 1 to 2 of time 10, 1 to 3 of time 1, and 3 to 2 of time 1, and send from node 1. Along the direct link, the signal reaches node 2 at time 10. Through node 3, it gets there at 1 + 1 = 2.
Node 2 hears it at time 2, and the copy that arrives at time 10 changes nothing. So each node hears the signal along its fastest route, and the total time of that route is called its shortest distance from k
That turns the problem into two smaller ones: find the shortest distance from k
Solution Approach
Turning that idea into code means settling four things: how to store the links, in which order to handle the nodes (with a slow way and a faster way), what to do with an arrival that was beaten, and how to read off the answer.
Storing the links
How does the code find the links that leave a node? Searching all of times
For Example 1, node 2's list holds {1, 1} and {3, 1}, node 3's list holds {4, 1}, and the lists of nodes 1 and 4 are empty. The nodes are numbered from 1, so the code makes n
The order of the nodes
Which node should pass the signal on next? Follow the clock. Keep, for every node, the earliest arrival time found so far, with "not reached yet" for the rest. Then always take the node with the smallest such time that has not been handled yet.
That node's time is already final. Any other route to it must pass through a node not handled yet, which is reached no earlier, and then add times that are not negative. Handling the node means checking each of its links: if a link gives the node at its other end an earlier arrival than the one stored, store the new time. This way of finding all shortest distances from one start node is called Dijkstra's algorithm, after the computer scientist Edsger Dijkstra.
How do we find the node with the smallest time? The simple way scans all nPriorityQueue
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
Each entry is a pair {node, arrival time}, so a[1]b[1]
Arrivals that were beaten
What happens to a heap entry when a faster route to its node turns up later? Go back to the three-node network. Node 1 adds {2, 10} and {3, 1} to the heap. {3, 1} comes out first, and its link to node 2 gives time 2, so {2, 2} goes in too.
Now the heap holds two entries for node 2. Taking {2, 10} out of the middle of a PriorityQueue
Reading off the answer
When the heap is empty, what do the stored times say? Each one is the shortest distance to that node. A node still marked "not reached yet" has no route from k
Java Solution
The method networkDelayTime
- First, build the adjacency list
: a list ofadj + 1 empty lists. For each entryn oft , add the pair {times ,t[1] } to the list of nodet[2] .t[0] - Create the array
of the earliest arrival times, withdist + 1 slots. Fill it withn , which stands for "not reached yet", and setInteger.MAX_VALUE to 0. Create the min-heapdist[k] and add the entry {pq , 0}.k - While
is not empty, take out its earliest entry,pq , with nodetop and timeu . Ifd is larger thand , the entry is stale, so skip it.dist[u] - Otherwise, go through each link
in the list ofe , which leads to nodeu in timev . Ife[1] is smaller thand + e[1] , store it indist[v] and add {dist[v] ,v } to the heap.dist[v] - Finally, a loop goes over nodes 1 to
. If somen is stilldist[i] , return -1. Otherwise keep the largest time inInteger.MAX_VALUE and return it.answer
The main
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
public class NetworkDelayTime {
public static int networkDelayTime(int[][] times, int n, int k) {
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++) {
adj.add(new ArrayList<>()); // slot 0 stays unused
}
for (int[] t : times) {
adj.get(t[0]).add(new int[] {t[1], t[2]}); // from u: {v, w}
}
int[] dist = new int[n + 1];
Arrays.fill(dist, Integer.MAX_VALUE); // not reached yet
dist[k] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
pq.add(new int[] {k, 0});
while (!pq.isEmpty()) {
int[] top = pq.poll(); // the earliest arrival waiting
int u = top[0];
int d = top[1];
if (d > dist[u]) {
continue; // an older, slower arrival
}
for (int[] e : adj.get(u)) {
int v = e[0];
if (d + e[1] < dist[v]) {
dist[v] = d + e[1]; // a faster way to reach v
pq.add(new int[] {v, dist[v]});
}
}
}
int answer = 0;
for (int i = 1; i <= n; i++) {
if (dist[i] == Integer.MAX_VALUE) {
return -1; // node i never hears the signal
}
answer = Math.max(answer, dist[i]); // the last node to hear it
}
return answer;
}
public static void main(String[] args) {
System.out.println(networkDelayTime(new int[][] {{2, 1, 1}, {2, 3, 1}, {3, 4, 1}}, 4, 2));
System.out.println(networkDelayTime(new int[][] {{1, 2, 1}}, 2, 1));
System.out.println(networkDelayTime(new int[][] {{1, 2, 1}}, 2, 2));
System.out.println(networkDelayTime(new int[][] {{1, 2, 10}, {1, 3, 1}, {3, 2, 1}}, 3, 1));
System.out.println(networkDelayTime(new int[][] {}, 1, 1));
System.out.println(networkDelayTime(new int[][] {{1, 2, 4}, {2, 3, 4}, {4, 1, 1}}, 4, 1));
}
}
Running it prints:
2
1
-1
2
0
-1
The answers 2, 1 and -1 on the opening lines match Examples 1, 2 and 3. Look at the fourth line, 2: in the three-node network, node 2 is reached through node 3 at time 2, not along the direct link at time 10, whose stale entry is skipped.
The fifth line is 0, because a single node already has the signal and nothing has to travel. The last line is -1: node 4's only link points from it to node 1, so no signal from node 1 ever reaches node 4.
Why does the last loop start at 1 and not at 0? Slot 0 of distInteger.MAX_VALUEmain
Complexity
The work is building the adjacency list, plus one heap push and one heap poll each time a link gives a node an earlier arrival. Here E is the number of links in times
- Time: O(n + E log E), because each link adds at most one entry to the heap, and each push or poll on a heap of up to E entries takes about log E steps.
- Space: O(n + E), because the adjacency list keeps one pair per link,
hasdist + 1 slots, and the heap can hold up to one entry per link, stale entries included.n
The algorithm is explained step by step, with more pictures, in