Sub topic 8
Stopping Early When Nothing Changes
This chapter assumes you already know the basic Bellman-Ford loop from the earlier chapters. That loop relaxes every edge in V-1 rounds and then makes one extra pass to look for negative cycles. You should also know why V-1 rounds are enough. Here we look at a small change that often saves most of that work: stop as soon as a full pass over the edges changes no distance.
The Idea
Bellman-Ford's main loop is a series of passes. In each pass, every edge (u, v, w) gets a chance to lower dist[v] to dist[u] + w. The V-1 bound is a worst case. It covers a shortest path that uses V-1 edges and an edge order that settles only one edge of that path per pass.
Most real inputs are kinder. Shortest paths often use only a few edges, and the edge list often happens to follow the paths in roughly the right order. When that happens, the distances reach their final values after a few passes. Every later pass checks every edge and changes nothing.
The fix is a single boolean flag:
- Set
changed = Falseat the start of each pass. - Set
changed = Truewhenever a relaxation lowers a distance. - If a pass ends with
changedstillFalse, stop.
Why Stopping Is Safe
A pass reads only the current dist array and the fixed edge list. If a pass changes nothing, the array at the end of the pass is the same as at the start. The next pass would see exactly the same input, so it would also change nothing, and so would every pass after it. The remaining rounds cannot do any work.
There is a stronger result. A pass with no changes means every edge satisfies
dist[v] <= dist[u] + w
which is the triangle inequality for the current estimates. Suppose a negative cycle v0 -> v1 -> ... -> vk = v0 were reachable from the source. Then all its vertices would have finite distances. Adding the inequality over the cycle's edges gives
sum of dist[vi] <= sum of dist[vi] + (total cycle weight)
so the total cycle weight would have to be at least 0. That contradicts the cycle being negative. A pass with no changes therefore proves that no negative cycle is reachable from the source. It is the same test the extra detection pass performs, run earlier.
An Instrumented Implementation
The function below counts passes so you can see the effect of early exit. It also reports whether it stopped early.
import math
def bellman_ford_counted(n, edges, source):
dist = [math.inf] * n
dist[source] = 0
passes = 0
for _ in range(n - 1):
passes += 1
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
# Fixed point reached: distances are final and
# no negative cycle is reachable from source.
return dist, passes, True
# All n-1 passes changed something; we must check explicitly.
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError('negative cycle reachable from source')
return dist, passes, False
# A chain 0 -> 1 -> 2 -> 3 -> 4, all weights 1
forward = [(0, 1, 1), (1, 2, 1), (2, 3, 1), (3, 4, 1)]
backward = list(reversed(forward))
print(bellman_ford_counted(5, forward, 0)) # ([0, 1, 2, 3, 4], 2, True)
print(bellman_ford_counted(5, backward, 0)) # ([0, 1, 2, 3, 4], 4, False)
# The running example from earlier chapters
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
print(bellman_ford_counted(4, edges, 0)) # ([0, 4, 1, 5], 2, True)The two chain runs show how much edge order matters. In forward order, one pass sets every distance, because each relaxation uses a value that was set earlier in the same pass. The second pass changes nothing and confirms the result. In backward order, each pass moves the "frontier" forward by only one edge. All four passes do real work, so the early exit never fires and the explicit check has to run.
On the running example, the first pass sets dist[1] = 4, dist[2] = 5, then lowers dist[2] to 4 + (-3) = 1, and sets dist[3] = 1 + 4 = 5. The second pass finds nothing to improve. That is two passes instead of three plus one check.
What Early Exit Does and Does Not Change
| Situation | Passes without early exit | Passes with early exit |
|---|---|---|
| Edges in topological order of a DAG | V-1, plus check | 2 |
| Shortest paths use at most k edges | V-1, plus check | at most k+1 |
| Worst-case edge order, long paths | V-1, plus check | V-1, plus check |
| Negative cycle reachable | V-1, plus check (raises) | V-1, plus check (raises) |
| Source has no outgoing edges | V-1, plus check | 1 |
The worst-case running time stays O(V·E). Early exit improves the best and typical cases. It does nothing for an adversarial input. A reachable negative cycle always forces the full V-1 passes, because some distance keeps dropping on every pass.
The bound "at most k+1 passes" holds whatever the edge order. After pass i, every vertex whose shortest path uses at most i edges already has its correct distance. That is the same induction that proves V-1 passes are enough. If every shortest path uses at most k edges, all distances are final after pass k, and pass k+1 changes nothing.
Gotchas
Use a strict comparison
The test must be dist[u] + w < dist[v], not <=. With <=, a zero-weight cycle, or even two equal-length paths, would "change" a distance to the value it already has. The flag would then be set on every pass and the early exit would never fire. If you also update pred inside that branch, the predecessors could switch back and forth between equal-cost choices.
Reset the flag every pass
changed = False belongs inside the outer loop. If you set it once before the loop, a change in pass 1 keeps the flag True forever and early exit is silently turned off. Your results stay correct, but the function runs slower, so tests that only check output will not catch this bug.
Infinity arithmetic
In Python, math.inf + w is still math.inf for any finite w, including negative ones. That means inf + w < inf is False, and unreachable vertices never set the flag. If you use a large integer sentinel such as 10**18 instead, adding a negative weight gives a number below the sentinel. That counts as a false "improvement" and can keep the loop running. Either use math.inf or skip edges whose dist[u] is the sentinel.
Floating-point weights
With real-valued weights, such as the logarithms used for currency arbitrage later in the tutorial, rounding can produce changes as small as 1e-16. These count as improvements. Bellman-Ford still terminates, because the loop is bounded by V-1 passes. However, tiny rounding changes can block the early exit and can make a near-zero cycle look negative. A common fix is to require dist[u] + w < dist[v] - eps for a small tolerance eps. Pick eps with care: if it is too large, you will miss genuine negative cycles whose weight is close to zero.
Early exit tells you nothing about unreachable cycles
The "no negative cycle" guarantee only covers cycles reachable from the source. A negative cycle in a part of the graph the source cannot reach never gets finite distances, so it never sets the flag. To check the whole graph, add a virtual source with zero-weight edges to every vertex. Johnson's algorithm uses the same trick.
Exercise
A graph has V = 1000 vertices and E = 5000 edges, and every shortest path from the source uses at most 6 edges. With early exit, what is the maximum number of passes, and roughly how many edge relaxation attempts is that compared with the version without early exit?
Show answer
At most 7 passes: 6 to settle all distances plus 1 that changes nothing. That is about 7 × 5000 = 35,000 relaxation attempts. Without early exit the algorithm runs 999 passes plus a check pass, about 1000 × 5000 = 5,000,000 attempts, roughly 140 times more.
Exercise
A colleague changes the relaxation test to if dist[u] + w <= dist[v]: on a graph that contains the edges (1, 2, 0) and (2, 1, 0). Their outputs are still correct, but the function now always runs all V-1 passes. Explain why.
Show answer
Once vertices 1 and 2 have equal finite distances, each zero-weight edge satisfies dist[u] + 0 <= dist[v]. The relaxation then "succeeds" without lowering anything and sets changed = True on every pass. The pass with no changes that triggers early exit never happens. Using strict < fixes it.
Exercise
Early exit fires after pass 3 on some graph. Is it necessary to run the separate negative-cycle detection pass afterward? Justify your answer.
Show answer
No. A pass with no changes means every edge already satisfies dist[v] <= dist[u] + w. Summing this inequality around any reachable cycle shows that the cycle's total weight is at least 0, so no negative cycle is reachable from the source. The detection pass would perform the same check and find nothing.