Sub topic 12
Stopping Early When You Only Need One Target
This chapter assumes you have read the earlier chapters on the heap-based implementation with lazy deletion and on why the greedy choice is correct. You should be comfortable with the dijkstra function and the idea that a vertex's distance is final once it is popped.
Many real queries ask for the distance between two specific vertices. A route planner wants the distance from home to the office, and it has no use for distances to every other address in the city. The full algorithm still computes all of them. Early termination lets you stop as soon as the answer you need is known.
Why Popping the Target Is Enough
The correctness chapter showed that, with non-negative weights, the vertex popped from the heap always has the smallest tentative distance among unvisited vertices. Any other route to that vertex has to leave the visited set through some vertex whose distance is at least as large, and adding non-negative edges cannot make that route shorter. So once a vertex is popped and is not a stale entry, its distance is final.
That rule covers the target too. When the target comes off the heap, its distance cannot improve, so you can return it.
The Implementation
The only change from the full version is a check placed right after the stale-entry test.
import heapq
def dijkstra_to_target(graph, source, target):
dist = {source: 0}
heap = [(0, source)]
visited = set()
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue
if u == target:
return d # final once popped, because weights are non-negative
visited.add(u)
for v, w in graph.get(u, []):
nd = d + w
if v not in dist or nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
return None
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}
print(dijkstra_to_target(graph, "A", "D")) # 4
print(dijkstra_to_target(graph, "D", "A")) # NoneIf you also want the path, keep the prev map from the path-reconstruction chapter and call reconstruct_path before returning. All predecessors on the target's shortest path are already recorded when the target is popped.
How Much It Saves
The early exit skips every vertex farther from the source than the target. Visited vertices form a growing "ball" around the source, ordered by distance, so the work depends on how close the target is.
| Situation | Effect of early termination |
|---|---|
| Target is near the source | Large savings; most of the graph is never touched |
| Target is among the farthest vertices | Almost no savings |
| Target is unreachable | No savings; the reachable part is fully explored before returning `None` |
| Many targets from the same source | Run the full algorithm once and reuse `dist` |
The worst-case complexity stays the same, O((V + E) log V) with a binary heap. Early termination makes the typical query faster, and the bound does not change.
The search still spreads out evenly in every direction, including away from the target. A* search, covered in the final chapter, keeps this early exit and adds a heuristic that pushes the search toward the target.
Exercise
Suppose you move the check so the function returns nd as soon as v == target during relaxation, before pushing. What does the function return for the query from A to D on the example graph, and why is it wrong?
Show answer
It returns 6. D is first reached when C is expanded, through the edge C-D with weight 5, giving 1 + 5 = 6. The shorter route A-C-B-D, costing 4, has not been discovered yet because B (distance 3) has not been popped. A tentative distance at push time is only an upper bound. It is guaranteed final only when the vertex is popped.
Exercise
Why does early termination give a correct answer only when every edge weight is non-negative?
Show answer
The early exit depends on the invariant that a popped vertex's distance is final. With a negative edge, a vertex popped later could reach the target through that edge and produce a shorter distance after the target was already returned.