Network Flow & Matching
Maximum flow, minimum cut and pairing things up.
In 1955 a then-secret RAND report by Harris and Ross modeled the Soviet rail network into Eastern Europe and asked two questions: how much can it carry, and what is the cheapest set of links to cut? Ford and Fulkerson proved that the two answers are always the same number. That theorem, max-flow min-cut, also assigns workers to jobs, routes disjoint paths, and selects profitable projects.
What you’ll learn
- Define flow networks, flows and cuts; build the residual graph and explain how its back edges let later augmenting paths undo earlier choices.
- State and prove the max-flow min-cut theorem and the integrality theorem, and bound Ford–Fulkerson by for integer capacities and Edmonds–Karp by .
- Reduce bipartite matching to flow, implement augmenting-path matching in , and know Hopcroft–Karp's and König's theorem.
- Model problems with super sources, vertex capacities, disjoint paths and minimum cuts, and recognize flow and matching problems and their look-alikes.
Flows and cuts
A network has edges s→a 7, s→b 10, a→c 8, a→d 3, b→c 13, b→d 3, c→d 3, c→t 7 and d→t 11. What is the capacity of the cut , ?
Show the answer
16
The edges from to are a→d 3, b→d 3, c→d 3 and c→t 7, which add up to 16; no edge goes from back to . So no flow can exceed 16. The cut gives only the weaker bound .
Every cut bounds every flow from above. The remarkable fact, proved in the next step, is that the bounds are tight: the largest flow equals the smallest cut, and an algorithm that finds the flow finds the cut as a by-product. On the network above, a flow of 16 exists.
Residual graphs and augmenting paths
The obvious algorithm: find any path from to with spare capacity, push as much as fits, repeat. On the network above, push s→a→c→t (7 units), then s→b→d→t (3), then s→b→c→d→t (3). That is 13, and now every path from is blocked: s→a is full, and from both exits are full. Yet 16 is possible. The first path sent all of a's flow through c, and the greedy algorithm cannot take that back.
The fix is to let a path undo flow. The residual graph has, for each edge , a forward arc with the spare capacity , and a back edge with capacity : sending flow along it cancels flow on . Arcs of capacity 0 are omitted. An augmenting path is an – path in , and its bottleneck is its smallest residual capacity. Here s→b→c→a→d→t uses the back edge c→a: b's units take over the a→c capacity, and three of a's units go via a→d instead. That adds 3 more, for 16.
FORD-FULKERSON(G, s, t):
f(u, v) ← 0 for every edge
while the residual graph G_f has a path P from s to t:
b ← min residual capacity on P # the bottleneck
for each arc of P:
if it is a forward arc (u, v): f(u, v) ← f(u, v) + b
else it is a back edge (v, u): f(u, v) ← f(u, v) − b
return fFord–Fulkerson (1956) is a method rather than one algorithm: it does not say which augmenting path to take. With integer capacities every bottleneck is at least 1, so it stops after at most augmentations, each found by a search in : in all, which is pseudo-polynomial.
(1) ⇒ (2). If an augmenting path existed, pushing its bottleneck would give a flow of value .
(2) ⇒ (3). Let be the set of vertices reachable from in ; then . An edge from to must be full, or its head would be reachable; an edge from to must be empty, or its back edge would make its tail reachable. So the net flow across the cut equals its capacity:
(3) ⇒ (1). By weak duality every flow is at most , so is maximum, and is a minimum cut.
Shortest augmenting paths: Edmonds–Karp
Even with integers, the choice of path matters. Take four vertices with edges s→u, s→v, u→t and v→t of capacity , and a middle edge u→v of capacity 1. Two paths, s→u→t and s→v→t, finish the job. But a bad choice alternates s→u→v→t and s→v→u→t, the second using the back edge v→u to undo the first: each pushes a single unit, and augmentations are needed. With , that is two billion searches for a flow that two would find.
Edmonds and Karp (1972) fixed this with one rule: always augment along a shortest path, found by breadth-first search. The number of augmentations is then whatever the capacities, so the running time is , polynomial in the size of the graph alone (the proof is in the Optimal lesson). Dinic's algorithm (1970) pushes many shortest paths per breadth-first search and runs in , or on unit-capacity matching networks.
In the four-vertex network just described, with , how many augmentations does the bad alternating choice of paths need before the flow is maximum?
Show the answer
2000
The maximum flow is , and each alternating path carries exactly 1 unit, limited by the middle edge or its back edge, so 2000 augmentations. Edmonds–Karp finds the two paths of length 2 first and stops after 2.
from collections import deque
class MaxFlow:
def __init__(self, n):
self.adj, self.to, self.cap = [[] for _ in range(n)], [], []
def add_edge(self, u, v, c): # edge i and its reverse i ^ 1 are stored together
for a, b, cc in ((u, v, c), (v, u, 0)):
self.adj[a].append(len(self.to)); self.to.append(b); self.cap.append(cc)
def max_flow(self, s, t):
flow = 0
while True:
via = [-1] * len(self.adj) # via[v]: the edge that reached v in this BFS
via[s], q = -2, deque([s])
while q and via[t] == -1:
u = q.popleft()
for e in self.adj[u]:
if self.cap[e] > 0 and via[self.to[e]] == -1:
via[self.to[e]] = e; q.append(self.to[e])
if via[t] == -1:
return flow # no augmenting path: the flow is maximum
path, v = [], t
while v != s:
path.append(via[v]); v = self.to[via[v] ^ 1]
b = min(self.cap[e] for e in path)
for e in path:
self.cap[e] -= b; self.cap[e ^ 1] += b # the reverse arc gains b
flow += bcap holds residual capacities, so there is no separate flow array: the flow on edge is the residual capacity of its reverse, . Storing each edge next to its reverse is the standard contest representation; it handles parallel edges and antiparallel pairs without special cases. On the example network, max_flow returns 16.
Matching as flow
A matching in a graph is a set of edges no two of which share a vertex. In a bipartite graph, with left side and right side , a maximum matching pairs as many vertices as possible: applicants with jobs they qualify for, students with seminars, rows with columns. Build a network: for every , for every edge, for every , all of capacity 1. An integral flow of value is exactly a matching of size , so by integrality a maximum flow is a maximum matching.
In this network an augmenting path alternates: it enters from at a free vertex, crosses to on an unmatched edge, comes back on a matched edge (a back edge), and so on, until it reaches a free vertex of . Flipping such an alternating path adds one pair. Searching for one from each left vertex in turn is Kuhn's algorithm, the simplest way to code a matching:
def max_matching(n_left, n_right, adj):
"""adj[u] = the right vertices that left vertex u may be matched with."""
match_r = [-1] * n_right # match_r[v] = left partner of v, or -1
def try_kuhn(u, seen):
for v in adj[u]:
if not seen[v]:
seen[v] = True
if match_r[v] == -1 or try_kuhn(match_r[v], seen):
match_r[v] = u # u takes v; v's old partner moved on
return True
return False
return sum(try_kuhn(u, [False] * n_right) for u in range(n_left))Each left vertex starts one search that visits every right vertex at most once, so the total is in the worst case. The recursion can go deep; in Python, raise the recursion limit or rewrite it with an explicit stack for large inputs.
Faster, and a min-max theorem. Hopcroft–Karp (1973) augments along a maximal set of vertex-disjoint shortest alternating paths per phase, needs only phases, and runs in . König's theorem (1931) says that in a bipartite graph the size of a maximum matching equals the size of a minimum vertex cover, the fewest vertices touching every edge. It is max-flow min-cut in disguise: a minimum cut of the matching network picks out a cover. Consequently a maximum independent set of a bipartite graph has minus the maximum matching vertices, although the problem is NP-hard in general graphs.
A board has some forbidden cells. You want to place as many rooks as possible on allowed cells so that no two share a row or a column. Which technique fits?
- Backtracking over the cells, row by row
- Greedy: in each row, put a rook in the first free column
- Bipartite matching between rows and columns, with an edge for every allowed cell
- Dynamic programming over subsets of used columns
Show the answer
C. Bipartite matching between rows and columns, with an edge for every allowed cell
A rook on cell uses row and column , and the condition says no row or column is used twice: that is exactly a matching in the bipartite graph of rows and columns whose edges are the allowed cells. Hopcroft–Karp solves boards of thousands of rows.
Modeling with flows
Most flow problems never mention flow. The skill is to build a network whose maximum flow, or minimum cut, is the answer. A few gadgets cover most cases:
| Need | Gadget |
|---|---|
| several sources or sinks | a super-source with an edge to each source (capacity = its supply, or ), and a super-sink likewise |
| a capacity on a vertex | split into with that capacity; edges into enter , edges out of leave |
| an undirected edge of capacity | two opposite arcs of capacity each |
| the most edge-disjoint – paths | capacity 1 on every edge: max flow = number of disjoint paths = fewest edges whose removal separates from (Menger, 1927) |
| vertex-disjoint paths | split every vertex, with capacity 1 |
| each worker takes at most jobs | capacity on the edge from the source to that worker |
Recognizing it
Signals. "Assign", "pair up", "match" each item with at most one (or ) partners; "the most disjoint routes"; "the fewest edges, vertices or links to remove so that cannot reach "; "send as much as possible through a network with limits"; two kinds of objects with compatibility constraints (a bipartite structure); a choice where taking one thing forces taking others (a closure, a minimum cut). Sizes are usually modest: up to a few thousand vertices for general flow, around edges for Hopcroft–Karp.
| Problem (in our words) | Key idea | Time |
|---|---|---|
| Assign applicants to jobs they qualify for, maximizing the number hired | Bipartite matching | (Hopcroft–Karp) |
| The fewest links to cut so that two servers can no longer communicate | Unit capacities; min cut = max number of edge-disjoint paths | for paths |
| Cover every marked cell of a grid with as few full rows or columns as possible | König: a minimum vertex cover of the rows–columns graph has the size of a maximum matching | |
| Choose projects with prerequisites to maximize total profit | Project selection: profit sum minus a minimum cut | one max flow |
| Can every student get one of their acceptable seminars, given seat limits? | student 1, student seminar 1, seminar seats; yes iff the max flow equals the number of students | one max flow |
Common bugs.
- Forgetting the reverse edge, or giving a directed edge's reverse capacity instead of 0 (only an undirected edge gets both ways).
- In Kuhn's algorithm, sharing one
seenarray across the whole run instead of resetting it for each left vertex. - An adjacency matrix for a sparse graph ( per search), or one that overwrites parallel edges instead of adding their capacities.
- An "infinite" capacity like that overflows when bottlenecks or cut values are summed in 64-bit arithmetic: use a bound just above the sum of all finite capacities.
- Reading the minimum cut before the flow is maximum, or from the wrong side: it is the set reachable from in the final residual graph.
- Deep recursion in depth-first augmenting searches, in Python or on large inputs.
A directed network has routers and links. You must find the fewest links whose failure would disconnect router from router . Which approach is right?
- Find a shortest – path with BFS and count its links
- Give every link capacity 1 and compute a maximum – flow
- Run Karger's random contraction algorithm
- Compute a minimum spanning tree and count the edges on the – tree path
Show the answer
B. Give every link capacity 1 and compute a maximum – flow
By Menger's theorem, the fewest links separating from equals the most link-disjoint – paths, which is the maximum flow with unit capacities; the residual graph then names the links to cut. With disjoint paths, plain augmenting paths cost .
Key takeaways
- Every flow is at most every cut. The residual graph has forward arcs with spare capacity and back edges that undo flow; an augmenting path is an – path in it.
- Max-flow min-cut: a flow is maximum iff no augmenting path exists iff it equals some cut's capacity; the vertices reachable from in the final residual graph give a minimum cut. Integer capacities give an integral maximum flow.
- Ford–Fulkerson costs with integer capacities and can be slow with bad paths; Edmonds–Karp's shortest paths need augmentations, in all, and Dinic runs in .
- Bipartite matching is unit-capacity flow, and its augmenting paths alternate. Kuhn's algorithm runs in , Hopcroft–Karp in , and König's theorem equates maximum matchings with minimum vertex covers.
- Model with super-sources, vertex splitting, unit capacities for disjoint paths and infinite edges for "taking this forces that". General matching, weighted assignment and global minimum cuts are different problems with their own algorithms.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does the residual graph contain back edges?
- So that the final flow may be negative on some edges
- So that a later augmenting path can cancel flow pushed earlier and reroute it
- Because flow networks are undirected
- To make breadth-first search faster
Show the answer
B. So that a later augmenting path can cancel flow pushed earlier and reroute it
An early path can commit capacity badly, as s→a→c→t did on the example network. Sending flow along the back edge c→a cancels some of that commitment, which is how Ford–Fulkerson escapes the dead end at 13 and reaches 16. The flow on each real edge stays between 0 and its capacity.
All capacities of a network are integers. Which statement is guaranteed?
- Every maximum flow sends an integer amount along every edge
- The maximum flow value may be a fraction
- Some maximum flow sends an integer amount along every edge, and Ford–Fulkerson finds one
- Only Edmonds–Karp is guaranteed to find an integral flow
Show the answer
C. Some maximum flow sends an integer amount along every edge, and Ford–Fulkerson finds one
Starting from zero, every bottleneck is an integer, so every intermediate flow is integral, including the final, maximum one. Other maximum flows can be fractional: if one unit must leave through a single edge of capacity 1 and can then continue along either of two parallel routes, sending half a unit along each is also a maximum flow.
Ford–Fulkerson has stopped. How do you find a minimum cut?
- Take every saturated edge
- Take the bottleneck edge of the last augmenting path
- Take the edges that carry no flow
- Let be the vertices reachable from in the residual graph; the edges from to the rest form a minimum cut
Show the answer
D. Let be the vertices reachable from in the residual graph; the edges from to the rest form a minimum cut
This is step (2) ⇒ (3) of the proof: every edge leaving the reachable set is full and every edge entering it is empty, so its capacity equals the flow value. It takes one more search after the last augmentation.
A bipartite graph has a maximum matching of 7 edges. What is the smallest number of vertices that together touch every edge?
- 7
- 14
- It cannot be determined from the matching size
Show the answer
A. 7
König's theorem: in a bipartite graph, a minimum vertex cover has exactly as many vertices as a maximum matching has edges. Any cover needs at least 7 vertices, one per matched edge, and the minimum cut of the matching network yields a cover of exactly 7.
Why is Edmonds–Karp polynomial while Ford–Fulkerson with arbitrary augmenting paths is not?
- Breadth-first search is asymptotically faster than depth-first search
- Edmonds–Karp never uses back edges
- With shortest paths, the number of augmentations is whatever the capacities are
- Each shortest path carries at least half of the remaining flow
Show the answer
C. With shortest paths, the number of augmentations is whatever the capacities are
Both searches cost ; the difference is how many are needed. Shortest augmenting paths make the residual distances non-decreasing, and each edge can be the bottleneck only times, so the count depends on and alone. Arbitrary paths can need a number of augmentations proportional to the capacities.
Go deeper
- Max-Flow Min-Cut in Depth · Ford–Fulkerson, Edmonds–Karp, Dinic and the duality theorem.
- Bipartite Matching & Assignment · Hopcroft–Karp, König’s theorem and the Hungarian algorithm.
- Maximum Flow in Almost-Linear Time · Interior-point methods, min-ratio cycles and the 2022 breakthrough.
Further reading
- L. R. Ford & D. R. Fulkerson, "Maximal flow through a network," Canadian Journal of Mathematics 8 (1956), 399–404.
- J. Edmonds & R. M. Karp, "Theoretical improvements in algorithmic efficiency for network flow problems," Journal of the ACM 19(2) (1972), 248–264.
- J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapter 7.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 24 and 25.