Sub topic 9
Edmonds-Karp: Choosing the Shortest Augmenting Path
This chapter assumes you know the Ford-Fulkerson method from earlier chapters: you build a residual graph, find any path from the source s to the sink t, and push the bottleneck amount along it. It also assumes you can write breadth-first search (BFS) and read Python lists and loops.
The previous chapter showed the weak spot of plain Ford-Fulkerson. The method never says which augmenting path to pick. With a poor choice, the number of augmentations can grow with the capacity values. With irrational capacities, the method may never stop. Edmonds-Karp removes that freedom with one rule:
Always augment along a shortest path in the residual graph, where "shortest" means the fewest edges.
BFS finds exactly such a path. The rest of the algorithm is the same as Ford-Fulkerson.
The Rule and Why It Helps
A shortest augmenting path counts edges and ignores capacities. That may seem odd, since you might expect to prefer paths that carry more flow. The edge-count rule has a property that capacity-based rules lack: the shortest-path distance from s to every vertex in the residual graph never decreases from one augmentation to the next.
Here is the intuition. Each augmentation saturates at least one edge on the path, the bottleneck edge, and removes it from the residual graph. The only new residual edges are reverse edges, and those point "backward," from a vertex farther from s to a vertex closer to s. A backward edge cannot create a shortcut. So distances can only stay the same or grow. Distances are bounded by V, so this gives a bound on the work that does not depend on the capacities. Chapter 12 turns this into the full O(V E^2) proof. In this chapter we use the rule and watch it work.
On the bad example from the previous chapter (two routes of capacity C joined by a middle edge of capacity 1), DFS can bounce across the middle edge 2C times. BFS picks the two direct two-edge paths first and finishes after two augmentations, whatever the value of C.
The Algorithm Step by Step
- Copy the capacities into a residual matrix.
- Run BFS from
s, following only edges with residual capacity greater than 0. Record each vertex's parent. - If BFS never reaches
t, stop. The current flow is maximum. - Walk the parent pointers back from
ttosand take the minimum residual capacity on the path. This is the bottleneck. - Along the path, subtract the bottleneck from each forward residual edge and add it to the matching reverse edge.
- Add the bottleneck to the total flow and return to step 2.
A Matrix Implementation
The version below stores the graph as an n x n capacity matrix. That keeps the reverse-edge bookkeeping simple: the reverse of u -> v is just residual[v][u]. Chapter 10 gives an adjacency-list version that scales better.
from collections import deque
def edmonds_karp(capacity, s, t):
# capacity is an n x n matrix; capacity[u][v] is the capacity of edge u -> v
n = len(capacity)
residual = [row[:] for row in capacity]
max_flow = 0
while True:
parent = [-1] * n
parent[s] = s
queue = deque([s])
while queue and parent[t] == -1:
u = queue.popleft()
for v in range(n):
if parent[v] == -1 and residual[u][v] > 0:
parent[v] = u
queue.append(v)
if parent[t] == -1:
return max_flow, residual
bottleneck = float('inf')
v = t
while v != s:
u = parent[v]
bottleneck = min(bottleneck, residual[u][v])
v = u
v = t
while v != s:
u = parent[v]
residual[u][v] -= bottleneck
residual[v][u] += bottleneck
v = u
max_flow += bottleneck
# Nodes: 0 = s, 1..4 = intermediate, 5 = t
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 0, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
]
flow, residual = edmonds_karp(capacity, 0, 5)
print(flow) # 23A few details are easy to miss:
parent[ source as visited. Without it, a reverse edge intoscould make BFS treats` as unvisited and overwrite its parent, which breaks the path walk.- A vertex is marked when it is enqueued, not when it is dequeued. Each vertex then enters the queue at most once.
- The BFS loop stops early once
thas a parent. This is safe because BFS reachestfirst along a shortest path. - The function returns
residualas well as the flow value. Chapter 11 uses it to find the minimum cut.
Each BFS on a matrix scans a full row per vertex, so one iteration costs O(V^2). That is fine for small or dense graphs. For sparse graphs, use the adjacency-list form.
Tracing the Example
Running the code on the network above gives three augmentations. BFS scans neighbors in index order, so the trace is deterministic.
| Iteration | Shortest path found | Edges | Bottleneck | Total flow |
|---|---|---|---|---|
| 1 | 0 → 1 → 3 → 5 | 3 | min(16, 12, 20) = 12 | 12 |
| 2 | 0 → 2 → 4 → 5 | 3 | min(13, 14, 4) = 4 | 16 |
| 3 | 0 → 2 → 4 → 3 → 5 | 4 | min(9, 10, 7, 8) = 7 | 23 |
| 4 | none: BFS reaches only {0, 1, 2, 4} | n/a | n/a | 23 |
Some points to check against the table:
- After iteration 1, edge
1 → 3is saturated (residual 0). In iteration 2, BFS still reaches vertex 1 through0 → 1, which has 4 units left, but vertex 1 is a dead end. - In iteration 3, the path uses residual values left over from earlier rounds:
0 → 2has 9 left (13 − 4) and2 → 4has 10 left (14 − 4). - Path lengths go 3, 3, 4. They never decrease, which matches the distance property described earlier.
- In the final BFS, the reachable set
{0, 1, 2, 4}is the source side of a minimum cut. Chapter 11 explains why.
This trace never sends flow along a reverse edge, but the algorithm does not depend on that. On other graphs a shortest path often uses reverse edges to undo flow sent earlier, and BFS treats them like any other edge with positive residual capacity.
Edmonds-Karp Compared with Other Path Choices
| Path choice | How it is found | Augmentation bound | Depends on capacities? |
|---|---|---|---|
| Any path (generic Ford-Fulkerson, DFS) | DFS | `O(f*)` for integer capacities, where `f*` is the max flow value | Yes; may not stop with irrational values |
| Shortest path (Edmonds-Karp) | BFS | `O(V E)` | No |
| Widest (fattest) path | Modified Dijkstra | `O(E log U)`, where `U` is the max capacity | Yes, logarithmically |
Multiplying O(V E) augmentations by O(E) per BFS gives the O(V E^2) total that Chapter 12 proves. Edmonds-Karp is the simplest choice with a guarantee that holds for any capacities, including real numbers.
Common Errors
- Using a stack or recursion instead of a queue. The code still returns a correct answer but becomes DFS-based Ford-Fulkerson, and the capacity-independent bound is lost. Check that you call
popleft(), notpop(). - Forgetting the reverse update. If you only subtract from
residual[u][v], the algorithm cannot undo bad choices and may return a flow below the maximum. - Overwriting the input. Augmenting
capacitydirectly destroys the original values, which you need later to read off flows (capacity[u][v] - residual[u][v]) or cut capacities. - Antiparallel edges in a matrix. If the input has both
u → vandv → u, the matrix still works because residuals add up correctly. But the per-edge flow can no longer be read ascapacity - residual. Either split one edge with an extra vertex or switch to paired edges. - Floating-point capacities. Residuals like
1e-17count as positive and cause extra iterations. Compare against a small epsilon or scale to integers.
Exercise
In the example network, suppose the capacity of edge 4 → 5 is raised from 4 to 10. Without running code, predict the first two augmenting paths Edmonds-Karp finds and their bottlenecks, then run the code to find the new maximum flow.
Show answer
The first BFS is unchanged: path 0 → 1 → 3 → 5 with bottleneck 12. The second BFS again finds 0 → 2 → 4 → 5, now with bottleneck min(13, 14, 10) = 10, for a total of 22. One more augmentation, 0 → 2 → 4 → 3 → 5, carries min(3, 4, 7, 8) = 3. The maximum flow is 25. You can confirm this with the cut {0, 1, 2, 4}: 12 (1 → 3) + 7 (4 → 3) + 10 (4 → 5) = 29 is not tight, so check the cut {0, 2, 4} instead: 16 (0 → 1) + 7 + 10 = 33, also not tight. The tight cut is around the source after saturation: 0 → 1 carries 12 and 0 → 2 carries 13, so 25 = 12 (1 → 3) + 13 (0 → 2), the cut {0, 1}.
Exercise
A classmate replaces queue.popleft() with queue.pop() and says all tests still pass. Explain why the tests can pass and what property the change destroys.
Show answer
With pop(), the deque acts as a stack, so the search becomes depth-first. Any search that finds some s-t path in the residual graph still gives a correct Ford-Fulkerson algorithm, so small tests with integer capacities return the right maximum flow. What is lost is the guarantee that each path is a shortest path. That guarantee is what makes distances non-decreasing and bounds the number of augmentations by O(V E) regardless of capacities. On inputs like the large-C example, the number of iterations can grow with the capacity values.