Pipes carry water from a reservoir s to a plant t. On this network the most that can arrive is 23 units a second. Three full pipes, of 12, 7 and 4, prove that no plan beats 23. A planner that cannot undo a choice stops at 19.
Pick a planner and press Run. Watch each path fill its pipes. Then we build, piece by piece: the two rules of flow, the residual network, augmenting paths, the min cut, matching and push-relabel.
You need directed graphs, BFS and a little Python. We build the rest from zero.
Based on Chapter 26 of Introduction to Algorithms (CLRS, third edition) by Cormen, Leiserson, Rivest and Stein. The network is the book's Figure 26.1, with v1 to v4 renamed a to d. It builds on Chapter 22, Graph Algorithms. The explanations, toys and devices are our own.
Capacities are CLRS Figure 26.1. Each pipe shows flow / capacity. Greedy and Ford-Fulkerson try neighbours in the order s, a, b, c, d, t.
Chapter 0
Fill paths by hand and watch a sensible plan get stuck below the best one
A city has one reservoir, s, and one treatment plant, t. Nine pipes join them through four junctions, a, b, c and d. Each pipe has a capacity: the most water it can carry each second. How much water can reach the plant each second?
A natural plan: find a path from s to t that still has room, fill it, and repeat. Be that planner below. Each button is a path. A press pushes as much water as the path's tightest pipe allows.
Press paths in any order. The small number on each button is the room it has left. A path with no room greys out.
These five buttons are every path from s to t that follows the pipe directions. The network can carry 23.
Press s, a, c, b, d, t, then s, a, c, t, then s, b, d, c, t. You carry 4 + 8 + 7 = 19, and every button greys out. The first path sent 4 units through c → b. That detour sent 4 units from c down to b, though c could send them straight to t. It also filled d → t, the pipe that water from s through b needed. To reach 23, the planner must be able to take a choice back.
This is the maximum flow problem: in a directed graph with capacities, send as much as possible from a source s to a sink t. Cars on roads and packets in a network fit the same form. So does matching people to tasks (Chapter 6).
The failure. Symptom: a path-filling planner reports 19 and stops. Measure: every path must use a → c, d → c or d → t, and those hold 12 + 7 + 4 = 23. A gap between 19 and 23 means the plan is not proven best. Fix: allow undo (Chapter 2), and prove the result with a cut (Chapter 5).
Chapter 1
Set the water on five pipes and find out which plans are legal
Take a smaller network. Pipes s → a and s → b hold 10 each, a cross pipe a → b holds 2, a → t holds 8 and b → t holds 12. A flow network is a directed graph like this one, with a capacity on each edge, a source and a sink.
A plan gives each pipe an amount of water. Call the amount on the pipe from u to v f(u, v), and its capacity c(u, v). The first rule: no pipe carries less than nothing or more than it can hold.
Zero is at most f of u v, and f of u v is at most c of u v.
For each pipe, check that f(u, v) is not negative and not above c(u, v).
The cross pipe has c(a, b) = 2. f(a, b) = 2 is legal. f(a, b) = 3 breaks the rule by 1 unit.
The second rule is about junctions. Water does not appear or vanish at a or b. What flows in, flows out.
For every vertex u other than s and t, the sum over v of f of v u equals the sum over v of f of u v.
At each junction u, add the water on the pipes into u. Add the water on the pipes out of u. The two totals must be equal.
Plan: f(s, a) = 10, f(a, b) = 2, f(a, t) = 8. At a, in is 10 and out is 2 + 8 = 10. The rule holds.
The value of a flow, written |f|, is the net water that leaves s: the total out of s minus any water that flows back into s. The maximum flow problem asks for a legal flow with the largest value.
Drag each slider. A pipe above its capacity turns red. Each junction shows its water in and out.
A made-up network. Sliders go 3 units past each capacity so that you can break the first rule.
Plan A sends 8 on s → a → t and 10 on s → b → t: |f| = 18. Plan B adds 2 on s → a → b → t: |f| = 20. Both pipes out of s are now full, and 10 + 10 = 20, so no plan can beat 20.
The failure. Symptom: a simulator reports more water at t than leaves s. Measure: at each junction, compute in minus out. Any nonzero value is a leak. Fix: check conservation after every update, as the device does.
Chapter 2
Draw the stalled plan as arrows of room and find the path that greedy could not see
Go back to the plan that stalled at 19. Pipes s → b and b → d still have room, but no path of pipes with room reaches t. The fix is a second kind of room: room to send less on a pipe that already carries water.
The residual network Gf shows both kinds. For each pipe it draws up to two arrows. A forward arrow shows the room left. A backward arrow shows how much flow you may cancel. Call the room of the arrow from u to v the residual capacity cf(u, v).
c-f of u v equals c of u v minus f of u v, and c-f of v u equals f of u v.
For each pipe u → v, draw a forward arrow with room c(u, v) − f(u, v). Draw a backward arrow v → u with room f(u, v). Leave out any arrow with room 0.
Pipe c → b has capacity 9 and carries 4. Forward room cf(c, b) = 9 − 4 = 5. Backward room cf(b, c) = 4.
Pushing 1 unit along the backward arrow b → c means that c sends 1 unit less to b. The water b got from c must now come from somewhere else, and c gains 1 unit to send elsewhere.
Switch to the residual view. Grey arrows are room left; purple arrows are undo room. Then press Augment.
The start is the stall of Chapter 0: paths s, a, c, b, d, t (4), s, a, c, t (8) and s, b, d, c, t (7).
In the residual view a path appears: s → b (room 6), the undo arrow b → c (room 4) and c → t (room 5). Its tightest arrow allows 4. Push 4: f(s, b) rises from 7 to 11, f(c, b) falls from 4 to 0, and f(c, t) rises from 15 to 19. Junction b still sends 11 into d, now all from s. The total is 23.
The failure. Symptom: code that searches only forward arrows stops below the maximum, here at 19. Measure: build the residual network and search it from s. If t is reachable, the flow is not maximum. Fix: give every pipe its reverse arrow when you build the graph.
Chapter 3
Step the method through four paths, one of them through an undo arrow
The Ford-Fulkerson method repeats one move. A path from s to t in the residual network is an augmenting path. Find one, push water along it, and search again.
How much can a path carry? Call the path p and the room of each arrow on it cf(u, v).
c-f of p equals the minimum, over the arrows u v on p, of c-f of u v.
Read the room on each arrow of p. The smallest one is cf(p). Any more water would overfill that arrow.
The first path on the big network is s, a, c, b, d, t. Its rooms are 16, 12, 9, 14 and 4. So cf(p) = 4, set by pipe d → t.
Each Step pushes the warm path and finds the next one. Switch views to see the arrows the search uses.
The search is depth-first and tries neighbours in the order s, a, b, c, d, t.
| Path | Rooms on the path | Push | Total |
|---|---|---|---|
| s, a, c, b, d, t | 16, 12, 9, 14, 4 | 4 | 4 |
| s, a, c, t | 12, 8, 20 | 8 | 12 |
| s, b, c, t | 13, 4 (undo), 12 | 4 | 16 |
| s, b, d, c, t | 9, 10, 7, 8 | 7 | 23 |
Path three cancels the 4 units of the first path's detour. With integer capacities, each push adds at least 1 unit. So the method stops after at most |f*| pushes, where |f*| is the maximum value. Each search costs O(E) for E pipes, so the total is O(E · |f*|).
The failure. Symptom: a max-flow routine passes small tests but returns too little on others. Measure: after each push, check that the flow on u → v and its reverse entry sum to zero. Fix: every push of b on u → v must also take b off v → u.
Chapter 4
Raise the capacities and watch an unlucky path choice slow down while BFS does not
Ford-Fulkerson does not say which path to pick. A bad pick can be slow. Take four vertices. Pipes s → a, s → b, a → t and b → t each hold C, and a cross pipe a → b holds 1. The maximum is 2C.
An unlucky search alternates two paths: s, a, b, t and s, b, a, t. The second one uses the undo arrow b → a. Each path carries 1 unit, so the run needs 2C pushes. With C = 1,000 that is 2,000 pushes.
Drag C, pick a search, then press Run. The bars count pushes on a log scale.
We force the unlucky choice on purpose, to show the worst case. A depth-first search can fall into it on graphs like this one.
Edmonds-Karp fixes the pick: always push along a shortest augmenting path, counted in arrows, found by BFS (Chapter 22). Here BFS finds s, a, t and s, b, t first. That is 2 pushes for any C.
Why does BFS help on every network? CLRS proves two facts. The BFS distance from s to each vertex never shrinks from one push to the next. And so each pipe can be the bottleneck at most V/2 times. Call the number of vertices V and the number of pipes E.
The number of pushes is at most E times V over 2.
Each push fills the arrow that is its bottleneck. Before that arrow can be the bottleneck again, its distance from s must grow by 2. Distances stop at V, so each of the E pipes gets that role at most V/2 times.
The big network has V = 6 and E = 9. The bound is 9 × 3 = 27 pushes. Edmonds-Karp uses 3: s, a, c, t (12), s, b, d, t (4) and s, b, d, c, t (7).
Each BFS costs O(E), so Edmonds-Karp runs in O(V E2). The capacities do not appear in the bound. For V = 1,000 and E = 10,000, the push bound is 5,000,000 whatever the capacities are.
The failure. Symptom: max flow takes minutes on a graph with large capacities. Measure: count pushes. If the count grows with the capacities, the search is not shortest-first. Fix: find each path with BFS.
Chapter 5
Move junctions between two sides and find the cut whose capacity equals the flow
How do we know that 23 is the most? Split the vertices in two, with s on one side and t on the other. Every unit of water must cross between the sides.
An s-t cut (S, T) splits the vertices into a set S that holds s and a set T that holds t. Its capacity is the total capacity of the pipes that go from S to T.
c of S T equals the sum, over u in S and v in T, of c of u v.
List the pipes that cross from S to T. Add their capacities. Pipes that cross from T back to S add nothing.
S = {s, a}. The pipes from S to T are s → b (13) and a → c (12). So c(S, T) = 25. Pipe b → a goes from T to S and does not count.
Now measure the water that crosses the same cut. Count pipes from S to T as plus and pipes from T to S as minus. Call this net crossing f(S, T).
The value of f equals f of S T, and f of S T is at most c of S T.
Junctions keep nothing, so the net water across any cut equals |f|. Forward pipes carry at most their capacity and backward pipes only subtract, so f(S, T) is at most c(S, T).
Take the flow of 23 and S = {s, a}: f(s, b) = 11 plus f(a, c) = 12, minus f(b, a) = 0, gives 23. That is at most c(S, T) = 25.
Toggle which junctions sit with s. Pink pipes cross from S to T. The flow is the maximum flow of 23.
There are 16 cuts, one for each choice of sides for a, b, c and d. Their capacities run from 23 to 62.
One cut hits 23 exactly, and Ford-Fulkerson hands it to you when it stops. Let S be every vertex the last search still reaches: {s, a, b, d}. Every pipe out of S is full, and the one pipe into S, c → b, is empty. So f(S, T) = c(S, T) = 12 + 7 + 4 = 23.
This is the max-flow min-cut theorem (CLRS Theorem 26.6). Three statements are the same: f is a maximum flow; the residual network has no augmenting path; |f| = c(S, T) for some cut. A minimum cut is a cut of least capacity, and its capacity equals the maximum flow value.
The failure. Symptom: a max-flow routine has a bug that no test catches. Measure: compare |f| with the capacity of the reachable cut. Fix: if they differ, the routine is wrong. The cut is a free check.
Chapter 6
Pair students with projects, then fix a greedy pairing with one augmenting path
Five students each list the projects they would take. Each student gets at most one project, and each project at most one student. How many pairs can you make?
This is maximum bipartite matching. A bipartite graph has two groups, L and R, and every edge joins L to R. A matching is a set of edges with no shared vertex. Flow solves it in four steps:
Why are the amounts whole? The integrality theorem (CLRS Theorem 26.10): with integer capacities, Ford-Fulkerson finds a max flow with integer amounts. So each pipe carries 0 or 1, and the unit pipes at s and t stop a student or a project from being used twice.
Press Greedy, then Augment. Tap a student, then a project, to add or remove an interest.
Made-up interests. Greedy gives each student, in order, the first free project on their list.
The interests: Ana {ML, Web}, Ben {ML}, Cy {DB, Web}, Dee {DB}, Eli {OS, UI}. Greedy pairs Ana with ML, Cy with DB and Eli with OS: 3 pairs. Ben and Dee get nothing.
Search the residual network from Ben. Ben → ML has room. ML is taken, but the undo arrow ML → Ana lets Ana give it up, and Ana → Web → t is free. Push 1: Ben gets ML, Ana moves to Web, and there are 4 pairs.
The search from Dee runs DB, Cy, Web, Ana, ML, Ben and dead-ends.
A proof of 4: ML, Web, DB and Eli touch every edge. A set of vertices that touches every edge is a vertex cover. Each pair needs its own cover vertex, so no matching beats 4. Kőnig's theorem says that in a bipartite graph the smallest cover equals the largest matching. The min cut gives that cover.
A matching has at most V/2 pairs, so there are at most V/2 pushes of O(E) each: O(VE).
The failure. Symptom: an assignment tool leaves Ben out, though a better pairing exists. Measure: for each unmatched student, search for an augmenting path. Fix: augment along it instead of stopping at first choices.
Chapter 7
Turn labelling a noisy image into a cut, then reduce three more problems to flow
Many problems are a min cut in disguise. The pattern: each choice becomes a side of the cut, and each cost becomes a pipe that the cut must sever.
Take a noisy image. Label each pixel object or background. Two costs apply. A pixel pays if its label disagrees with its brightness. A pair of neighbours pays λ (lambda) if their labels differ, because objects are mostly smooth.
A cut gives every pixel a label, and its capacity is exactly the total cost. So the min cut is the cheapest labelling.
| Labels (pixel 1, pixel 2) | Cost at λ = 0 | Cost at λ = 3 |
|---|---|---|
| object, object | 1 + 6 = 7 | 7 |
| object, background | 1 + 4 = 5 (best) | 5 + 3 = 8 |
| background, background | 9 + 4 = 13 | 13 |
Two neighbouring pixels have brightness 9 and 4 on a scale of 0 to 10. Calling a pixel object costs 10 minus its brightness; calling it background costs its brightness. At λ = 0, pixel 2 is background. At λ = 3, splitting costs 8, so pixel 2 joins the object for 7 (the best row).
Left: the noisy image. Right: the labels from the min cut. Drag λ and watch the specks vanish.
An illustrative image: a disc of brightness 7 on a background of 3, plus random noise. A red dot marks a label that differs from the hidden disc. Each λ runs a fresh Edmonds-Karp on 102 vertices.
Three more reductions, each from CLRS or its exercises:
| Problem | Build | Answer |
|---|---|---|
| Most paths from s to t with no shared edge | capacity 1 on every edge | the max flow value |
| Most paths with no shared middle vertex | split each vertex v into vin → vout with capacity 1 | the max flow value |
| Several sources and sinks | a super source with endless pipes to each source; a super sink the same way | one max flow |
The failure. Symptom: the mask is full of specks. Measure: count neighbour pairs with different labels. Fix: raise λ. In the device, λ = 1 cuts the wrong pixels from 18 to 4, and from λ = 6 the whole disc vanishes. Tune λ on images with known answers.
Chapter 8
Step a vertex-by-vertex method that floods first and drains the surplus later
Augmenting paths work on whole paths. Push-relabel, from Goldberg and Tarjan (1988), works on one vertex at a time. Picture each vertex at a height. Water may only run downhill, one level at a time.
In the middle of a run, a junction may hold more water than it sends on. This state is a preflow. The surplus at u is its excess. A vertex other than s and t with excess is active.
How high does u go? Call u's height h(u), and look only at the arrows u → v that have room.
h of u becomes one plus the minimum, over arrows u v whose room c-f of u v is above zero, of h of v.
Among the arrows out of u that have room, find the lowest neighbour v. Set h(u) to h(v) + 1. Now u can push to v.
On the big network, a holds 4 extra units after it fills a → c. Its only arrow with room is the undo arrow back to s, and h(s) = 6. So h(a) = 1 + 6 = 7, and a pushes its 4 units back to s.
Each vertex sits at its height. Yellow numbers are excess. Step through the 2 fills and 24 operations.
Generic push-relabel on CLRS Figure 26.1. Active vertices wait in a first-in, first-out queue. Each tries its neighbours in the order s, a, b, c, d, t.
The run takes 2 initial fills, 13 pushes and 11 relabels. Water reaches t through c → t (12, then 7) and d → t (4). Vertices b and d trade the last units back and forth, rising each time, until b climbs to 7 and returns 2 units to s. The result is 23 again. Six units went back to s: 4 from a and 2 from b.
| Method | Time | Idea |
|---|---|---|
| Generic push-relabel | O(V2 E) | any active vertex, any order (CLRS 26.4) |
| Relabel-to-front | O(V3) | discharge vertices from a list, move a lifted one to the front (CLRS 26.5) |
| Dinitz | O(V2 E) | BFS levels, then all shortest paths at once (a blocking flow) |
The failure. Symptom: the program never ends; two vertices trade the same units forever. Measure: log the pushes. The same pair repeats with no relabel between. Fix: push only when h(u) = h(v) + 1. Then a vertex must rise before it pushes back, and CLRS shows that no height passes 2V − 1.
Chapter 9
Keep the terms, the numbers, the checks and the code in one place
A flow obeys capacity and conservation. The residual network adds undo arrows. Push along augmenting paths until none is left, and the vertices you can still reach form a cut whose capacity equals your flow. That cut is the proof.
| Term | Meaning | Number from this lesson |
|---|---|---|
| Capacity rule | 0 ≤ f(u, v) ≤ c(u, v) | f(a, b) = 3 breaks c = 2 |
| Conservation | in = out at every junction | at a: 10 in, 2 + 8 out |
| Residual room | c − f forward, f backward | c → b: 5 forward, 4 undo |
| Bottleneck | smallest room on the path | 16, 12, 9, 14, 4: push 4 |
| Greedy, no undo | fill paths, never cancel | stalls at 19 |
| Edmonds-Karp | shortest path by BFS | 3 pushes; bound 27 |
| Min cut | reachable set after the last search | {s, a, b, d}: 12 + 7 + 4 = 23 |
| Matching | unit pipes s → L → R → t | greedy 3, max 4 |
| Push-relabel | push downhill, lift when stuck | 13 pushes, 11 relabels |
| Algorithm | Path choice | Time |
|---|---|---|
| Ford-Fulkerson (1956) | any augmenting path | O(E · |f*|) with integer capacities |
| Dinitz (1970) | blocking flow on BFS levels | O(V2 E); O(E √V) for bipartite matching (Hopcroft-Karp) |
| Edmonds-Karp (1972) | shortest path by BFS | O(V E2) |
| Push-relabel (1988) | no paths; local pushes | O(V2 E) generic, O(V3) relabel-to-front |
| Chen and others (2022) | interior-point method with dynamic data structures | E1 + o(1), almost linear |
pythonfrom collections import deque, defaultdict def max_flow(edges, s, t): # edges: list of (u, v, capacity) cap = defaultdict(int); adj = defaultdict(set) for u, v, c in edges: cap[u, v] += c adj[u].add(v); adj[v].add(u) # the reverse arrow too flow = defaultdict(int) # flow[v, u] == -flow[u, v] room = lambda u, v: cap[u, v] - flow[u, v] total = 0 while True: par = {s: None}; q = deque([s]) # BFS: shortest path first while q and t not in par: u = q.popleft() for v in adj[u]: if v not in par and room(u, v) > 0: par[v] = u; q.append(v) if t not in par: # no augmenting path: done return total, set(par) # par holds the min-cut side S path, v = [], t while par[v] is not None: path.append((par[v], v)); v = par[v] b = min(room(u, v) for u, v in path) # the bottleneck for u, v in path: flow[u, v] += b; flow[v, u] -= b total += b def max_matching(pairs): # pairs: list of (student, project) E = [('s', ('L', a), 1) for a in {a for a, _ in pairs}] E += [(('R', b), 't', 1) for b in {b for _, b in pairs}] E += [(('L', a), ('R', b), 1) for a, b in pairs] return max_flow(E, 's', 't')[0] net = [('s','a',16), ('s','b',13), ('b','a',4), ('a','c',12), ('c','b',9), ('b','d',14), ('d','c',7), ('c','t',20), ('d','t',4)] print(max_flow(net, 's', 't')) # (23, {'s', 'a', 'b', 'd'}) print(max_matching([('Ana','ML'), ('Ana','Web'), ('Ben','ML'), ('Cy','DB'), ('Cy','Web'), ('Dee','DB'), ('Eli','OS'), ('Eli','UI')])) # 4
Max flow is a linear program, and min cut is its dual (Chapter 29). Give each pipe a cost per unit as well, and the cheapest maximum flow comes from shortest paths by cost instead of by arrows (Chapter 24). Matching in graphs that are not bipartite needs Edmonds' blossom algorithm, a different method.
Now press Present or Teach and explain from memory. Say why greedy stalls at 19 and what a backward arrow does. Say why Edmonds-Karp does not care about capacities, and how the last search gives the min cut. Then go back to the pipes and run all three planners. This time, name the chapter behind each colour.
This lesson re-teaches Chapter 26, Maximum Flow, of Introduction to Algorithms (third edition) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). Figure and theorem numbers follow that edition.
The method is from L. R. Ford and D. R. Fulkerson (1956); the BFS rule from Jack Edmonds and Richard Karp (1972) and, independently, Yefim Dinitz (1970); push-relabel from Andrew Goldberg and Robert Tarjan (1988). The almost-linear algorithm is by Li Chen, Rasmus Kyng, Yang Liu, Richard Peng, Maximilian Probst Gutenberg and Sushant Sachdeva (2022). The text, toys and devices here are our own.