Find when a signal can first reach every node in a directed network with fixed travel costs.
Problem
Input. A positive node_count, a valid start node, and directed edges [source, target, cost] using IDs 1..node_count.
Output. Return the latest earliest-arrival time among all nodes, or -1 if any node is unreachable from start.
Rules. The signal starts at time zero. Edge costs are fixed and nonnegative; path cost is their sum. Edges are directed, so reverse travel is not implied. Preserve the edge list. This is shortest-path timing, not congestion-aware packet simulation.
Example. Use edges [[1, 2, 1], [1, 3, 4], [2, 3, 2], [2, 4, 6], [3, 4, 1]].
Starting at node 1 with four nodes gives earliest arrivals [0, 1, 3, 4]; return 4.
Picture
The heap stores candidate routes; the finalized map stores accepted shortest distances. Several routes can name the same node.
| Popped candidate | Action |
|---|---|
(0,1) | Finalize 1; offer (1,2) and (4,3) |
(1,2) | Finalize 2; offer (3,3) and (7,4) |
(3,3) | Finalize 3; offer (4,4) |
(4,3) | Skip already finalized 3 |
(4,4) | Finalize 4 |
(7,4) | Skip already finalized 4 |
Problem trace
Separate queued estimates: stale entries do not replace the finalized minimum
Reference drawing
Problem trace
A stale heap entry cannot improve an already finalized shorter distance
Execution trace
- visited
- []
- edges
- [1 -1-> 2, 1 -4-> 3, 2 -2-> 3, 2 -6-> 4, 3 -1-> 4]
- edge label mode
- weight
- visited
- []→[1:0]
- relaxation
- not shown→1->2 gives 1; 1->3 gives 4
- input
- n=4, start=1→not shown
- visited
- [1:0]→[1:0, 2:1]
- start
- 1→2
- relaxation
- 1->2 gives 1; 1->3 gives 4→2->3 gives 3; 2->4 gives 7
- visited
- [1:0, 2:1]→[1:0, 2:1, 3:3]
- start
- 2→3
- relaxation
- 2->3 gives 3; 2->4 gives 7→3->4 gives 4
- decision
- not shown→skip duplicate node 3
- relaxation
- 3->4 gives 4→not shown
- visited
- [1:0, 2:1, 3:3]→[1:0, 2:1, 3:3, 4:4]
- start
- 3→4
- decision
- skip duplicate node 3→skip later (7,4)
- result
- not shown→4
- start
- 4→not shown
- decision
- skip later (7,4)→not shown
- Recognize it
- The input is a directed graph with nonnegative edge costs, and the task asks when a source reaches every node, so shortest paths from one source determine the answer.
- Keep true
- Whenever an unfinalized node is popped with the globally smallest pending cost, that cost is its shortest distance; duplicate heap entries for finalized nodes are safely ignored.
- Reuse it
- Reuse Dijkstra for nonnegative weighted routing: enqueue improved path candidates, trust only the first pop of each node, and derive the requested aggregate from finalized shortest distances.
Why is the first pop final? Any supposedly cheaper route crosses from a finalized predecessor to a first unfinalized node. That predecessor already offered the corresponding prefix. Nonnegative remaining edges cannot make that prefix more expensive than the complete route. A cheaper complete route would therefore require a cheaper pending prefix, contradicting the minimum pop.
Code
This reference offers every outgoing candidate whose target is not finalized. It does not maintain a separate tentative-best table or perform decrease-key updates.
import heapq
from collections import defaultdict
def network_delay_time(times: list[list[int]], node_count: int, start: int) -> int:
graph: dict[int, list[tuple[int, int]]] = defaultdict(list)
for source, target, cost in times:
graph[source].append((target, cost))
distances: dict[int, int] = {}
heap = [(0, start)]
while heap:
distance, node = heapq.heappop(heap)
if node in distances:
continue
distances[node] = distance
for neighbor, cost in graph[node]:
if neighbor not in distances:
heapq.heappush(heap, (distance + cost, neighbor))
return max(distances.values()) if len(distances) == node_count else -1
Each node expands at most once, so each edge offers at most one candidate. The heap can hold entries, not just . For general multigraphs, bounds are time and space. For simple graphs, the usual bound follows.
Failure Check
Do not finalize at enqueue time or use FIFO order for unequal costs.
Negative costs invalidate the proof.
For [[1,2,1],[1,3,2],[3,2,-5],[2,4,2]], this method returns 3.
The true maximum shortest arrival is 2; node 2 should arrive at -3.
Change the Sources
New task: Return each node’s nearest arrival from simultaneous zero-time sources.
Picture and change: Seed all sources before popping anything.
Use the same valid node universe and nonnegative-cost contract.
Unreached nodes return None, in node-ID order.
def arrival_times(times, node_count, starts):
graph = {node: [] for node in range(1, node_count + 1)}
for source, target, cost in times:
graph[source].append((target, cost))
heap = [(0, source) for source in set(starts)]
heapq.heapify(heap)
finalized = {}
while heap:
distance, node = heapq.heappop(heap)
if node in finalized:
continue
finalized[node] = distance
for neighbor, cost in graph[node]:
if neighbor not in finalized:
heapq.heappush(heap, (distance + cost, neighbor))
return [finalized.get(node) for node in range(1, node_count + 1)]
Check: Edges [[1,2,3],[3,2,1]] with sources [1,3] return [0,1,0].
No sources returns all None; duplicate sources are coalesced.
Keep the reference’s heapq import above.
Reading a seed iterable also costs its length.
Use when: The nearest of several simultaneous sources matters.
Change the Query
New task: Return nodes reached by an inclusive deadline.
Picture and change: Compute arrivals first, then filter finite results.
def reached_by(times, node_count, starts, deadline):
arrivals = arrival_times(times, node_count, starts)
return [
node for node, distance in enumerate(arrivals, 1)
if distance is not None and distance <= deadline
]
Check: [[1,2,1],[2,3,2]], source [1], deadline 1 returns [1,2].
The boundary is inclusive; an unreachable node never passes.
This wrapper does not stop the search early or change its shortest-path proof.
Use when: The arrival query changes, not the path costs.
Transfer Check
Why can two heap entries refer to the same node?
Answer
Different routes can be discovered before the cheapest one is popped. The finalized-node guard discards later duplicates safely under the nonnegative-cost contract. Compare equal-cost frontiers before replacing the heap with a queue.