Sub topic 10
Implementing Edmonds-Karp with Paired Edges
This chapter assumes you know how BFS works on an adjacency list, what a residual graph is, and how Edmonds-Karp repeatedly augments along the shortest path in it. Earlier chapters used an adjacency matrix to make the residual graph easy to see. Here you will replace it with an adjacency-list representation that real solvers use. In this representation every edge is stored right next to its reverse.
Why the Matrix Version Stops Scaling
The matrix version scans all n possible neighbours of every vertex it dequeues. One BFS therefore costs O(V²), even when the graph has only a few edges. A road network with a million intersections has only a few million roads, but a matrix for it would need 10¹² cells.
The matrix also merges edges that share endpoints. Two parallel pipes from u to v with capacities 3 and 5 become a single cell holding 8. That gives the correct flow value, but you can no longer report how much flow each pipe carries. The same thing happens to antiparallel edges u → v and v → u: the original edge and the reverse residual edge end up in the same cell.
| Property | Adjacency matrix | Paired adjacency list |
|---|---|---|
| Memory | O(V²) | O(V + E) |
| Cost of one BFS | O(V²) | O(V + E) |
| Total Edmonds-Karp time | O(V³E) | O(VE²) |
| Parallel edges | Merged into one cell | Kept separate |
| Flow on each original edge | Lost when edges merge | Always recoverable |
| Finding the reverse edge | `residual[v][u]` | `e ^ 1` |
The O(VE²) bound from the analysis chapter assumes each BFS costs O(E). Only the list representation actually meets that assumption.
The Paired-Edge Layout
All edges live in two flat parallel arrays:
to[e]is the head of edgee, the vertex it points to.cap[e]is the current residual capacity of edgee.
Each vertex u keeps a list graph[u] of the indices of edges that leave it. That list includes reverse edges, because they are edges of the residual graph too.
add_edge(u, v, c) always appends two entries in a row. It adds the forward edge u → v with capacity c, then the reverse edge v → u with capacity 0. Indexing starts at 0, so forward edges get even indices (0, 2, 4, …) and their reverses get the odd index directly after (1, 3, 5, …).
That layout makes the partner of any edge easy to find. Flipping the lowest bit of an index maps 2k to 2k+1 and back, so e ^ 1 is always the partner edge. You never need a lookup table.
The arrays do not store the tail of an edge, the vertex it starts from. You get it from the partner instead: the tail of e is to[e ^ 1]. When BFS backtracks from the sink, it uses this to step from a vertex to its predecessor.
The Full Implementation
BFS records parent_edge[v], the edge used to reach v, rather than the parent vertex. With parallel edges, knowing the parent vertex does not tell you which edge to update.
from collections import deque
class MaxFlow:
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)] # edge indices leaving each node
self.to = []
self.cap = []
def add_edge(self, u, v, c):
# Edge e and its reverse e ^ 1 are stored next to each other
self.graph[u].append(len(self.to))
self.to.append(v)
self.cap.append(c)
self.graph[v].append(len(self.to))
self.to.append(u)
self.cap.append(0)
def max_flow(self, s, t):
flow = 0
while True:
parent_edge = [-1] * self.n
visited = [False] * self.n
visited[s] = True
queue = deque([s])
while queue and not visited[t]:
u = queue.popleft()
for e in self.graph[u]:
v = self.to[e]
if not visited[v] and self.cap[e] > 0:
visited[v] = True
parent_edge[v] = e
queue.append(v)
if not visited[t]:
return flow
bottleneck = float('inf')
v = t
while v != s:
e = parent_edge[v]
bottleneck = min(bottleneck, self.cap[e])
v = self.to[e ^ 1]
v = t
while v != s:
e = parent_edge[v]
self.cap[e] -= bottleneck
self.cap[e ^ 1] += bottleneck
v = self.to[e ^ 1]
flow += bottleneck
# Same network as the matrix version: 0 = s, 5 = t
mf = MaxFlow(6)
for u, v, c in [(0, 1, 16), (0, 2, 13), (1, 3, 12), (2, 1, 4),
(2, 4, 14), (3, 2, 9), (3, 5, 20), (4, 3, 7), (4, 5, 4)]:
mf.add_edge(u, v, c)
print(mf.max_flow(0, 5)) # 23How the Pieces Map to the Algorithm
- BFS over residual edges. The test
self.cap[e] > 0is the definition of a residual edge. Forward and reverse edges go through the same test, so cancelling flow needs no special case. - Early exit. The loop condition
not visited[t]stops the BFS once the sink is reached. The path is already a shortest path at that point, so exploring further is wasted work. - Bottleneck walk. The first walk from
tback tostakes the minimum residual capacity along the path. - Augment. The second walk lowers
cap[e]and raisescap[e ^ 1]by the same amount. This single pair of lines handles both pushing new flow and cancelling old flow.
Reading Back the Flow on Each Edge
Because of that invariant, the flow on an original edge e (an even index) equals cap[e ^ 1]. The reverse capacity started at 0 and has risen by exactly the net amount pushed forward. Add the following to the end of the script above:
def edge_flows(mf):
# Returns (tail, head, flow) for each original edge
result = []
for e in range(0, len(mf.to), 2):
result.append((mf.to[e ^ 1], mf.to[e], mf.cap[e ^ 1]))
return result
flows = edge_flows(mf)
for u, v, f in flows:
print(f"{u} -> {v}: {f}")
out_of_source = sum(f for u, v, f in flows if u == 0)
print(out_of_source) # 23The flows on individual edges depend on the order in which BFS visits neighbours, which follows the order of add_edge calls. The total leaving the source is always 23. Different runs can give different maximum flows with the same value.
Common Mistakes
Storing the Parent Vertex Instead of the Parent Edge
If you store parent[v] = u and then search graph[u] for an edge pointing to v, you may pick the wrong one of two parallel edges. You may even pick one with zero residual capacity, which makes the bottleneck 0 and the loop never ends. Store the edge index.
Not Starting the Edge Index at Zero, or Inserting Single Edges
The e ^ 1 trick only works if pairs start at an even index. If you ever append a lone edge, or start a 1-based edge counter at 1, every pair after it is misaligned. Then e ^ 1 points at an unrelated edge, and the results are silently wrong rather than crashing.
Giving Each Undirected Edge Two Separate Pairs
An undirected edge of capacity c can be stored as one pair whose reverse capacity is also c, instead of 0. Two separate directed pairs also give a correct answer but use twice the memory. The modeling-tricks chapter covers this case.
Floating-Point Capacities
With float capacities, a residual of 1e-17 still passes cap[e] > 0. That can lead to long runs of tiny augmentations. Scale to integers when you can, or compare against a small epsilon.
Edge Cases Worth Knowing
s == t.visited[t]is true before the loop starts. The code then walks zero steps and adds an infinite bottleneck to the flow, so it returnsinfor loops forever. Reject this input up front.- Self-loops.
add_edge(u, u, c)is harmless because BFS never revisitsu. It still costs two array slots. - Zero-capacity edges. These are legal and never used. They do make each BFS scan more entries.
- Unreachable sink. The first BFS fails and the method returns 0, which is correct.
Performance Notes for Python
Flat lists of ints are much faster in CPython than a list of Edge objects with attributes, because there is less pointer chasing and no attribute lookup. For graphs with more than about 10⁵ edges, Edmonds-Karp in pure Python becomes slow no matter how it is laid out. At that size, switch to Dinic's algorithm, which uses the same paired-edge layout, or call a compiled library.
Exercise
After addedge(3, 7, 5) is the fifth call to addedge on a fresh MaxFlow object, what are the indices of the new forward and reverse edges, and what expression gives the tail of the forward edge?
Show answer
Each call adds two entries, so the first four calls use indices 0 to 7. The fifth call creates forward edge 8 (to[8] = 7, cap[8] = 5) and reverse edge 9 (to[9] = 3, cap[9] = 0). The tail of edge 8 is to[8 ^ 1] = to[9] = 3.
Exercise
Add two parallel edges 0 -> 1 with capacities 3 and 5, and an edge 1 -> 2 with capacity 10, then compute max_flow(0, 2). What is the result, and why would a version that stores parent vertices instead of parent edges be at risk here?
Show answer
The maximum flow is 8, because both parallel edges are used in full. A parent-vertex version has to search graph[0] for some edge pointing to vertex 1. Once one of the parallel edges is saturated, the search may return that edge, whose residual capacity is 0. The bottleneck then becomes 0, the flow stops growing, and the loop can run forever.
Exercise
Prove that after any number of augmentations, cap[e ^ 1] equals the net flow on original edge e (e even) with capacity c.
Show answer
Initially cap[e] = c and cap[e ^ 1] = 0, so the sum is c and the flow is 0. Each augmentation that uses e subtracts b from cap[e] and adds b to cap[e ^ 1]. Each augmentation that uses e ^ 1 does the opposite. Both keep the sum equal to c. Every push along e increases the net flow by b and every push along e ^ 1 decreases it by b, so the net flow always equals c - cap[e], which is cap[e ^ 1].