Sub topic 12
Stopping Early When You Only Need One Target
Many real queries ask for one distance, such as "how far is the warehouse from this customer?", not for a full table of distances from the source. Dijkstra's algorithm can answer that kind of question with less work. This chapter shows exactly when it is safe to stop, the mistakes people make when they stop too soon, and how much work early termination actually saves.
This chapter assumes you know the heap-based implementation with lazy deletion and the predecessor map from earlier chapters. It also assumes you know the greedy invariant: with non-negative weights, a vertex's distance is final once that vertex is popped from the heap.
The Stopping Rule
The rule is short. Stop when the target is popped from the heap. Do not stop when it is first discovered or relaxed.
The correctness chapter showed why this rule works. When a vertex u comes off the heap with distance d, every other path to u must go through some vertex that is still in the heap. Each of those vertices has a tentative distance of at least d. Edge weights are non-negative, so extending such a path can only keep its cost the same or raise it. No later work can produce a value lower than d. The full algorithm would keep going and fill in other vertices, but it would never change dist[target] again. Stopping at that pop gives the same answer as the full run.
Lazy deletion does not interfere. Stale heap entries for the target always carry larger distances than the live entry, so the first time the target comes off the heap, it comes off with its true distance. The visited check runs before the target check, so a stale entry can never be mistaken for the answer.
A Complete Single-Target Implementation
The version below returns the distance, the path, and a count of how many vertices were finalized. The count lets you measure the savings. Because the target's predecessor chain consists only of vertices that were already popped, every prev entry on that chain is final, and the path can be rebuilt right away.
import heapq
def dijkstra_to_target(graph, source, target):
"""Return (distance, path, pops). distance and path are None if unreachable."""
dist = {source: 0}
prev = {}
heap = [(0, source)]
visited = set()
pops = 0
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue # stale entry from lazy deletion
pops += 1
if u == target:
path = [u]
while path[-1] != source:
path.append(prev[path[-1]])
path.reverse()
return d, path, pops
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
prev[v] = u
heapq.heappush(heap, (nd, v))
return None, None, pops
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [("E", 10)],
"E": [],
}
print(dijkstra_to_target(graph, "A", "D")) # (4, ['A', 'C', 'B', 'D'], 4)
print(dijkstra_to_target(graph, "A", "Z")) # (None, None, 5)The first call finalizes A, C, B, and D, then stops. It never pops E. The second call asks for a vertex that does not exist, so the loop drains the heap: it finalizes all 5 vertices and then reports that the target is unreachable. This shows the worst case of early termination. When the target is unreachable, you pay for the full search.
Two edge cases behave correctly without extra code:
target == source: the first pop is the source, so the function returns(0, [source], 1)without relaxing any edge.- Unreachable target: the heap empties and the function returns
None. You cannot detect unreachability any sooner, because some vertex still in the heap might lead to the target.
The Common Mistake: Stopping on Discovery
It is tempting to return as soon as you relax an edge into the target. After all, you now have a distance for it. That distance is only an upper bound.
import heapq
def stop_on_discovery(graph, source, target):
"""WRONG: returns the first tentative distance found for target."""
dist = {source: 0}
heap = [(0, source)]
visited = set()
while heap:
d, u = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
for v, w in graph.get(u, []):
nd = d + w
if v == target:
return nd # premature: a cheaper route may still exist
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(stop_on_discovery(graph, "A", "D")) # 5, but the true distance is 4The search reaches D first through the direct edge C→D, at a cost of 5. The cheaper route A→C→B→D shows up only after B is popped at distance 3. Breadth-first search on unweighted graphs can stop on discovery, because there the first discovery is always optimal. That habit carries over badly to weighted graphs.
| Stopping point | Correct? | Why |
|---|---|---|
| Target first relaxed or pushed | No | The tentative distance is only an upper bound |
| Target popped (non-stale) | Yes | The greedy invariant makes it final |
| Heap empty | Yes | This is the full algorithm, with no savings |
How Much Work Does It Save?
Early termination finalizes exactly the vertices whose distance is less than the target's distance. It also finalizes some of the vertices whose distance equals the target's, depending on how ties are broken. The search region is a "ball" around the source with a radius equal to the target's distance. The savings depend on where the target falls in that distance ordering, not on the size of the graph.
On a grid, the effect is easy to see:
def grid(n):
g = {}
for i in range(n):
for j in range(n):
nbrs = []
for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
a, b = i + di, j + dj
if 0 <= a < n and 0 <= b < n:
nbrs.append(((a, b), 1))
g[(i, j)] = nbrs
return g
g = grid(30)
d, path, pops = dijkstra_to_target(g, (0, 0), (3, 3))
print(d, len(path), pops) # 6 7 25
_, _, full = dijkstra_to_target(g, (0, 0), "none")
print(full) # 900The near target needs 25 pops out of 900. Of those, 21 are vertices at distance 5 or less, and 4 are at distance 6. The tuple comparison pops (0, 6), (1, 5), and (2, 4) before (3, 3). For a target in the far corner, the search would finalize nearly the whole grid.
Variations
Several targets. Keep a set of the targets not yet popped. Remove each target as it is popped, and stop when the set is empty. The cost is set by the farthest target in the group.
import heapq
def dijkstra_to_targets(graph, source, targets):
remaining = set(targets)
found = {}
dist = {source: 0}
heap = [(0, source)]
visited = set()
while heap and remaining:
d, u = heapq.heappop(heap)
if u in visited:
continue
visited.add(u)
if u in remaining:
found[u] = d
remaining.discard(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 found # targets missing from the result are unreachableA distance budget. If you only care about vertices within distance R, such as "all stores within 10 km", stop when the popped d exceeds R. Everything popped before that point is final, and nothing beyond it can be within the budget.
Pruning the search region. Even with early exit, Dijkstra searches evenly in every direction, including directions that lead away from the target. Guiding the search toward the target is the idea behind A*, covered in the final chapter.
Exercises
Exercise
On the five-vertex graph from the implementation section, a colleague moves the check if u == target above the if u in visited: continue line. Does this change any result? When could the order matter?
Show answer
On that graph the result does not change. The first pop of D is the live entry at distance 4, and the function returns immediately, so no stale entry for D is ever popped. In general the first pop of the target always carries the minimum distance, so swapping the checks still returns the correct value. The order would matter if the loop continued after seeing the target, for example in a multi-target version. There, checking before visited would process stale target entries again and could overwrite found[u] with a larger, wrong value. Keeping the stale-entry filter first is the safe habit.
Exercise
Graph: S→A weight 1, S→T weight 10, A→B weight 1, B→T weight 1, plus edges B→X1, X1→X2, ..., X999→X1000, each with weight 5. How many vertices does dijkstratotarget(graph, "S", "T") finalize, and how many would the full algorithm finalize?
Show answer
Distances are S=0, A=1, B=2, T=3, X1=7, and so on. The early-exit version pops S, A, B, and then T, for 4 pops. It never pops any X vertex, because X1 enters the heap at 7, which is larger than 3. The full algorithm finalizes all 1004 vertices.
Exercise
Why can't you return early with "unreachable" when the target has not been discovered after k pops, for any fixed k?
Show answer
Any vertex still in the heap might have an edge to the target, possibly through a long chain of cheap edges. Until the heap is empty, the target could still be reached, so you can only report it unreachable after the search runs out of vertices.