Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

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 O(m ∣f∗∣)O(m\,\abs{f^*}) for integer capacities and Edmonds–Karp by O(nm2)O(nm^2).
  • Reduce bipartite matching to flow, implement augmenting-path matching in O(nm)O(nm), and know Hopcroft–Karp's O(mn)O(m\sqrt n) 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

Predict before you look

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 S={s,a,b,c}S = \{s, a, b, c\}, T={d,t}T = \{d, t\}?

Show the answer

16

The edges from SS to TT are a→d 3, b→d 3, c→d 3 and c→t 7, which add up to 16; no edge goes from TT back to SS. So no flow can exceed 16. The cut S={s}S = \{s\} gives only the weaker bound 7+10=177 + 10 = 17.

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 ss to tt 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 ss is blocked: s→a is full, and from cc 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 GfG_f has, for each edge (u,v)(u, v), a forward arc with the spare capacity c(u,v)−f(u,v)c(u, v) - f(u, v), and a back edge (v,u)(v, u) with capacity f(u,v)f(u, v): sending flow along it cancels flow on (u,v)(u, v). Arcs of capacity 0 are omitted. An augmenting path is an ss–tt path in GfG_f, 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.

text
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 f

Ford–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 ∣f∗∣\abs{f^*} augmentations, each found by a search in O(m)O(m): O(m ∣f∗∣)O(m\,\abs{f^*}) in all, which is pseudo-polynomial.

DerivationProof
  1. augmenting path⟹∣f∣ is not maximum\text{augmenting path} \Longrightarrow \abs{f} \text{ is not maximum}

    (1) ⇒ (2). If an augmenting path existed, pushing its bottleneck b>0b > 0 would give a flow of value ∣f∣+b\abs{f} + b.

  2. ∣f∣=f(S→T)−f(T→S)=c(S,T)−0\abs{f} = f(S \to T) - f(T \to S) = c(S, T) - 0

    (2) ⇒ (3). Let SS be the set of vertices reachable from ss in GfG_f; then t∉St \notin S. An edge from SS to TT must be full, or its head would be reachable; an edge from TT to SS must be empty, or its back edge would make its tail reachable. So the net flow across the cut equals its capacity:

  3. ∣f′∣≤c(S,T)=∣f∣for every flow f′\abs{f'} \le c(S, T) = \abs{f} \quad\text{for every flow } f'

    (3) ⇒ (1). By weak duality every flow is at most c(S,T)=∣f∣c(S, T) = \abs{f}, so ff is maximum, and (S,T)(S, T) 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 CC, 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 2C2C augmentations are needed. With C=109C = 10^9, 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 O(nm)O(nm) whatever the capacities, so the running time is O(nm2)O(nm^2), 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 O(n2m)O(n^2 m), or O(mn)O(m\sqrt n) on unit-capacity matching networks.

Predict before you look

In the four-vertex network just described, with C=1000C = 1000, how many augmentations does the bad alternating choice of paths need before the flow is maximum?

Show the answer

2000

The maximum flow is 2C=20002C = 2000, 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.

python
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 += b

cap holds residual capacities, so there is no separate flow array: the flow on edge ii is the residual capacity of its reverse, i⊕1i \oplus 1. 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 LL and right side RR, a maximum matching pairs as many vertices as possible: applicants with jobs they qualify for, students with seminars, rows with columns. Build a network: s→us \to u for every u∈Lu \in L, u→vu \to v for every edge, v→tv \to t for every v∈Rv \in R, all of capacity 1. An integral flow of value kk is exactly a matching of size kk, so by integrality a maximum flow is a maximum matching.

In this network an augmenting path alternates: it enters LL from ss at a free vertex, crosses to RR on an unmatched edge, comes back on a matched edge (a back edge), and so on, until it reaches a free vertex of RR. 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:

python
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 O(nm)O(nm) in the worst case. The recursion can go nn 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 O(n)O(\sqrt n) phases, and runs in O(mn)O(m\sqrt n). 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 nn minus the maximum matching vertices, although the problem is NP-hard in general graphs.

Check your understanding

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?

  1. Backtracking over the cells, row by row
  2. Greedy: in each row, put a rook in the first free column
  3. Bipartite matching between rows and columns, with an edge for every allowed cell
  4. 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 (r,c)(r, c) uses row rr and column cc, 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:

NeedGadget
several sources or sinksa super-source with an edge to each source (capacity = its supply, or ∞\infty), and a super-sink likewise
a capacity on a vertexsplit vv into vin→voutv_{\text{in}} \to v_{\text{out}} with that capacity; edges into vv enter vinv_{\text{in}}, edges out of vv leave voutv_{\text{out}}
an undirected edge of capacity cctwo opposite arcs of capacity cc each
the most edge-disjoint ss–tt pathscapacity 1 on every edge: max flow = number of disjoint paths = fewest edges whose removal separates ss from tt (Menger, 1927)
vertex-disjoint pathssplit every vertex, with capacity 1
each worker takes at most kk jobscapacity kk on the edge from the source to that worker
After building the network, check that every integral flow corresponds to a valid solution and every solution to a flow of the same value; then integrality does the rest.

Recognizing it

Signals. "Assign", "pair up", "match" each item with at most one (or kk) partners; "the most disjoint routes"; "the fewest edges, vertices or links to remove so that AA cannot reach BB"; "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 10510^5 edges for Hopcroft–Karp.

Problem (in our words)Key ideaTime
Assign applicants to jobs they qualify for, maximizing the number hiredBipartite matchingO(mn)O(m\sqrt n) (Hopcroft–Karp)
The fewest links to cut so that two servers can no longer communicateUnit capacities; min cut = max number of edge-disjoint pathsO(km)O(km) for kk paths
Cover every marked cell of a grid with as few full rows or columns as possibleKönig: a minimum vertex cover of the rows–columns graph has the size of a maximum matchingO(mn)O(m\sqrt n)
Choose projects with prerequisites to maximize total profitProject selection: profit sum minus a minimum cutone max flow
Can every student get one of their acceptable seminars, given seat limits?s→s \to student 1, student →\to seminar 1, seminar →t\to t seats; yes iff the max flow equals the number of studentsone max flow
For unit-capacity problems, the O(km)O(km) bound of plain augmenting paths, where kk is the answer, is often all you need.

Common bugs.

  • Forgetting the reverse edge, or giving a directed edge's reverse capacity cc instead of 0 (only an undirected edge gets cc both ways).
  • In Kuhn's algorithm, sharing one seen array across the whole run instead of resetting it for each left vertex.
  • An adjacency matrix for a sparse graph (O(n2)O(n^2) per search), or one that overwrites parallel edges instead of adding their capacities.
  • An "infinite" capacity like 101810^{18} 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 ss in the final residual graph.
  • Deep recursion in depth-first augmenting searches, in Python or on large inputs.
Check your understanding

A directed network has n=2000n = 2000 routers and m=104m = 10^4 links. You must find the fewest links whose failure would disconnect router ss from router tt. Which approach is right?

  1. Find a shortest ss–tt path with BFS and count its links
  2. Give every link capacity 1 and compute a maximum ss–tt flow
  3. Run Karger's random contraction algorithm
  4. Compute a minimum spanning tree and count the edges on the ss–tt tree path
Show the answer

B. Give every link capacity 1 and compute a maximum ss–tt flow

By Menger's theorem, the fewest links separating ss from tt equals the most link-disjoint ss–tt paths, which is the maximum flow with unit capacities; the residual graph then names the links to cut. With kk disjoint paths, plain augmenting paths cost O(km)O(km).

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 ss–tt 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 ss in the final residual graph give a minimum cut. Integer capacities give an integral maximum flow.
  • Ford–Fulkerson costs O(m ∣f∗∣)O(m\,\abs{f^*}) with integer capacities and can be slow with bad paths; Edmonds–Karp's shortest paths need O(nm)O(nm) augmentations, O(nm2)O(nm^2) in all, and Dinic runs in O(n2m)O(n^2 m).
  • Bipartite matching is unit-capacity flow, and its augmenting paths alternate. Kuhn's algorithm runs in O(nm)O(nm), Hopcroft–Karp in O(mn)O(m\sqrt n), 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.

Question 1

Why does the residual graph contain back edges?

  1. So that the final flow may be negative on some edges
  2. So that a later augmenting path can cancel flow pushed earlier and reroute it
  3. Because flow networks are undirected
  4. 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.

Question 2

All capacities of a network are integers. Which statement is guaranteed?

  1. Every maximum flow sends an integer amount along every edge
  2. The maximum flow value may be a fraction
  3. Some maximum flow sends an integer amount along every edge, and Ford–Fulkerson finds one
  4. 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 ss 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.

Question 3

Ford–Fulkerson has stopped. How do you find a minimum cut?

  1. Take every saturated edge
  2. Take the bottleneck edge of the last augmenting path
  3. Take the edges that carry no flow
  4. Let SS be the vertices reachable from ss in the residual graph; the edges from SS to the rest form a minimum cut
Show the answer

D. Let SS be the vertices reachable from ss in the residual graph; the edges from SS 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.

Question 4

A bipartite graph has a maximum matching of 7 edges. What is the smallest number of vertices that together touch every edge?

  1. 7
  2. 14
  3. n−7n - 7
  4. 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.

Question 5

Why is Edmonds–Karp polynomial while Ford–Fulkerson with arbitrary augmenting paths is not?

  1. Breadth-first search is asymptotically faster than depth-first search
  2. Edmonds–Karp never uses back edges
  3. With shortest paths, the number of augmentations is O(nm)O(nm) whatever the capacities are
  4. Each shortest path carries at least half of the remaining flow
Show the answer

C. With shortest paths, the number of augmentations is O(nm)O(nm) whatever the capacities are

Both searches cost O(m)O(m); the difference is how many are needed. Shortest augmenting paths make the residual distances non-decreasing, and each edge can be the bottleneck only O(n)O(n) times, so the count depends on nn and mm alone. Arbitrary paths can need a number of augmentations proportional to the capacities.

Go deeper

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.