Example 1
- Input
- times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2
- Output
- 2
Nodes 1 and 3 hear the signal at time 1, and node 4 hears it through node 3 at time 2.
A signal leaves node k and fans out along every directed link at once, each link adding its own travel seconds. Return when the last of the n nodes hears the signal, or -1 when some node is unreachable.
You are given a network of n nodes labelled 1 to n and a list times where times[i] = [u, v, w] is a directed edge: a signal needs w seconds to travel from u to v.
Send a signal from node k. It fans out along every link simultaneously, so each node hears it via its fastest route. Return the time when the last node receives the signal, or -1 if some node can never receive it.
1 <= k <= n <= 1001 <= times.length <= 6000times[i].length == 31 <= u, v <= nu != v0 <= w <= 100(u, v) pair appears twice.Nodes 1 and 3 hear the signal at time 1, and node 4 hears it through node 3 at time 2.
The single link carries the signal to node 2 in one second.
The only link is 1 -> 2. Starting at node 2 cannot traverse it backwards, so node 1 never hears the signal even though the undirected network would be connected.
The direct arrival at node 2 would be 9, but 1 -> 3 -> 2 takes only 1 because the second link costs zero. Node 4 then arrives at 3. The fastest arrivals are [0, 1, 1, 3]; a heap may still contain the obsolete (9,2) route, which must be skipped.
Each node receives the signal along its fastest directed route from k; these shortest arrival times happen in parallel, so the answer is their maximum, not their sum. In Example 1, arrivals for nodes 1 through 4 are [1, 0, 1, 2], making the delay 2. Relaxing an edge means improving its destination arrival using a known arrival at its source plus the edge weight. Bellman-Ford repeats all such checks; Dijkstra uses non-negative weights to settle the smallest pending arrival first. A node with no route from k makes the entire answer -1.
Reveal Bellman Ford Relax All: intuition, complexity, and code
-1.-1 rather than a partial maximum.n nodes were settled, which reports a time for unreachable graphs.Single-source arrival times on non-negative weights belong to Dijkstra: always expand the closest unsettled node and read the answer off the largest settled distance.