Sub topic 8
Stopping Early When Nothing Changes
This chapter assumes you know the basic Bellman-Ford loop from the previous chapters: up to V-1 passes over every edge, then one extra pass to check for negative cycles. It also assumes you can read Big-O notation. Here we look at one small addition, the changed flag, and what it does and does not buy you.
The idea
Each pass of Bellman-Ford tries to relax every edge. Suppose a full pass finishes and no distance went down. The next pass would see exactly the same dist array, so it would also change nothing. The same holds for every pass after that. The distances have reached a fixed point, so the remaining passes would only repeat work.
So we track whether any relaxation succeeded during the pass. If none did, we stop.
A version that counts passes
This variant reports how many passes it actually ran. That makes the effect of the flag easy to see.
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: no edge can be relaxed, so no reachable negative cycle
return dist, passes
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError('negative cycle reachable from source')
return dist, passes
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)
chain_fast = [(0, 1, 1), (1, 2, 1), (2, 3, 1)]
chain_slow = [(2, 3, 1), (1, 2, 1), (0, 1, 1)]
print(bellman_ford_counted(4, chain_fast, 0)) # ([0, 1, 2, 3], 2)
print(bellman_ford_counted(4, chain_slow, 0)) # ([0, 1, 2, 3], 3)In the first graph, pass 1 already finds every final distance. Pass 2 only confirms that, and the loop exits. The two chains show that edge order matters. When the edges are listed in path order, one pass spreads the distances all the way down the chain. When they are listed in reverse, each pass moves the distances forward by only one edge, so the loop needs the full V-1 passes.
Skipping the negative cycle check
When the loop exits early, the final check is unnecessary. The check asks "can any edge still be relaxed?", and a pass that changed nothing has just answered "no". This is why the function above returns right away. The version in the earlier chapter breaks out of the loop and runs the check anyway. That is correct, but it costs one extra pass over the edges.
What it costs and saves
| Case | Passes run | Time |
|---|---|---|
| Best (good edge order, shallow paths) | 1 to 2 | O(E) |
| Typical | about (edges in longest shortest path) + 1 | between the two |
| Worst (reverse order, long paths) | V-1, plus check | O(VE) |
| Reachable negative cycle | V-1, plus check | O(VE) |
The worst-case bound stays O(VE). Early exit is a practical speedup, and the asymptotic cost does not change. The flag costs one boolean assignment per successful relaxation, so it is always worth adding.
Exercise
On a graph with V = 1000, a run with early exit stops after pass 7. What can you conclude about the shortest paths from the source and about negative cycles?
Show answer
Pass 7 relaxed nothing, so pass 6 had already reached the fixed point. Every shortest path from the source therefore uses at most about 6 edges under this edge ordering, and no negative cycle is reachable from the source, because a reachable negative cycle would keep at least one edge relaxable on every pass.
Exercise
Reorder the edges of chain_slow so the run takes exactly 2 passes, and explain why 1 pass is impossible here.
Show answer
Use path order: (0,1), (1,2), (2,3). Pass 1 sets every distance. A second pass is still required to observe that nothing changes, because the algorithm cannot know it has converged until a pass makes no improvement.