AnyLearn
All lessons
Mathintermediate

Network Flows: Augmenting Paths and the Max-Flow Min-Cut Theorem

Why pushing flow greedily gets stuck, how the residual graph makes every decision reversible, and why the maximum flow always equals the minimum cut. Build Edmonds-Karp in Python, compare the classic algorithms, and see cuts solve image segmentation and project selection.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 10

A flow network, precisely

A flow network is a directed graph with a source ss, a sink tt, and a nonnegative capacity c(u,v)c(u,v) on each arc. A flow assigns a number f(u,v)f(u,v) to every arc subject to two rules:

0≤f(u,v)≤c(u,v)(capacity)0 \le f(u,v) \le c(u,v) \qquad \text{(capacity)}

∑wf(w,v)=∑wf(v,w)for every v≠s,t(conservation)\sum_{w} f(w,v) = \sum_{w} f(v,w) \quad \text{for every } v \ne s,t \qquad \text{(conservation)}

What enters an intermediate vertex leaves it. The value ∣f∣\lvert f\rvert is the net amount leaving ss, which by conservation equals the net amount arriving at tt. The maximum flow problem asks for the largest possible value.

Definition: An ss-tt cut (S,T)(S, T) splits the vertices into two sides with s∈Ss \in S and t∈Tt \in T. Its capacity is the total capacity of arcs pointing from SS to TT; arcs pointing back from TT to SS do not count.

The model fits anything that is conserved while moving: packets through routers, freight through rail yards, water through pipes, and, more abstractly, "units of assignment" through a bipartite graph, which is where the next lesson takes it.

Sign in free to save your progress and earn certificates.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. A flow network, precisely

A flow network is a directed graph with a source ss, a sink tt, and a nonnegative capacity c(u,v)c(u,v) on each arc. A flow assigns a number f(u,v)f(u,v) to every arc subject to two rules:

0≤f(u,v)≤c(u,v)(capacity)0 \le f(u,v) \le c(u,v) \qquad \text{(capacity)}

∑wf(w,v)=∑wf(v,w)for every v≠s,t(conservation)\sum_{w} f(w,v) = \sum_{w} f(v,w) \quad \text{for every } v \ne s,t \qquad \text{(conservation)}

What enters an intermediate vertex leaves it. The value ∣f∣\lvert f\rvert is the net amount leaving ss, which by conservation equals the net amount arriving at tt. The maximum flow problem asks for the largest possible value.

Definition: An ss-tt cut (S,T)(S, T) splits the vertices into two sides with s∈Ss \in S and t∈Tt \in T. Its capacity is the total capacity of arcs pointing from SS to TT; arcs pointing back from TT to SS do not count.

The model fits anything that is conserved while moving: packets through routers, freight through rail yards, water through pipes, and, more abstractly, "units of assignment" through a bipartite graph, which is where the next lesson takes it.

2. Why pushing along any open path fails

The obvious algorithm: find any ss-tt path with spare capacity, push as much as it allows, repeat until no path is left. It can get stuck well short of the optimum.

Predict first

Five arcs, each of capacity 1: s→as \to a, s→bs \to b, a→ba \to b, a→ta \to t, b→tb \to t. The greedy method happens to pick the path s→a→b→ts \to a \to b \to t first and pushes 1 unit. What flow value does it end with, and what is the true maximum?

The first choice was not wrong in a way you could have seen locally. Every path looked equally good. The fix is not to search harder for the right first path; it is to make every decision reversible, so a later path can cancel flow that an earlier one placed on a→ba \to b.

3. The residual graph makes every push undoable

Given a current flow ff, the residual graph GfG_f records every way the flow could still change. For each arc (u,v)(u,v) of the network it contains up to two arcs:

Residual arcResidual capacityMeaning
forward u→vu \to vc(u,v)−f(u,v)c(u,v) - f(u,v)room left to push more
backward v→uv \to uf(u,v)f(u,v)flow already sent that could be cancelled

Arcs with zero residual capacity are dropped. An augmenting path is any ss-tt path in GfG_f. Pushing bb units along it, where bb is the smallest residual capacity on the path (the bottleneck), raises ∣f∣\lvert f\rvert by bb and keeps both rules intact.

In the stuck example, GfG_f contains the backward arc b→ab \to a with capacity 1. The path s→b→a→ts \to b \to a \to t uses it: one unit enters bb from ss, the cancellation reroutes the earlier unit at aa toward tt, and the value rises to 2.

Key idea: A backward arc is not physical flow running the wrong way. It is bookkeeping for "change your mind", and it is what lets a sequence of locally chosen paths reach a global optimum.

4. The Ford-Fulkerson loop

The method Ford and Fulkerson published in 1956 is a loop over the residual graph. It stops when tt becomes unreachable from ss, and at that moment the search itself hands you a minimum cut: the set of vertices it could still reach.

flowchart TD
  A["Start with zero flow"] --> B["Build residual graph"]
  B --> C["Search for an s to t path"]
  C --> D["Path found: take its bottleneck b"]
  D --> E["Add b forward, subtract b on reversed arcs"]
  E --> B
  C --> F["No path: stop"]
  F --> G["Vertices reachable from s form side S of a min cut"]

5. Max-flow min-cut: the certificate

Every flow is bounded by every cut, because all flow from ss to tt must cross from SS to TT somewhere:

∣f∣  ≤  c(S,T)for every flow f and every s-t cut (S,T)\lvert f\rvert \;\le\; c(S, T) \quad \text{for every flow } f \text{ and every } s\text{-}t \text{ cut } (S,T)

Ford and Fulkerson (1956), and independently Elias, Feinstein and Shannon (1956), proved the gap always closes. The following are equivalent:

  1. ff is a maximum flow.
  2. The residual graph GfG_f has no augmenting path.
  3. ∣f∣=c(S,T)\lvert f\rvert = c(S,T) for some cut (S,T)(S,T).

The proof of 2 implies 3 is constructive. Let SS be everything reachable from ss in GfG_f. Every arc from SS to TT must be full (or its forward residual arc would extend SS), and every arc from TT to SS must be empty (or its backward residual arc would). So exactly c(S,T)c(S,T) crosses, and the bound is met.

Key idea: This is a duality with a certificate on each side. A flow of value 17 proves the maximum is at least 17; a cut of capacity 17 proves it is at most 17. Show both and nobody needs to trust your algorithm. Menger's theorem from the previous lesson is the special case with unit capacities.

6. Edmonds-Karp in about thirty lines

Choosing the augmenting path by breadth-first search, so always a shortest one, is the Edmonds-Karp rule. The function returns the flow value and the source side of a minimum cut.

from collections import deque

def max_flow(cap, s, t):
    # cap[u][v] = capacity of arc u -> v
    res = {u: dict(nbrs) for u, nbrs in cap.items()}
    for u in cap:
        for v in cap[u]:
            res.setdefault(v, {}).setdefault(u, 0)   # backward arcs
    flow = 0
    while True:
        parent = {s: None}
        q = deque([s])
        while q and t not in parent:                 # BFS: shortest path
            u = q.popleft()
            for v, c in res[u].items():
                if c > 0 and v not in parent:
                    parent[v] = u
                    q.append(v)
        if t not in parent:
            return flow, set(parent)                 # reachable = side S
        path, v = [], t
        while parent[v] is not None:
            path.append((parent[v], v))
            v = parent[v]
        b = min(res[u][v] for u, v in path)          # bottleneck
        for u, v in path:
            res[u][v] -= b
            res[v][u] += b
        flow += b

cap = {"s": {"a": 3, "b": 2}, "a": {"b": 1, "t": 2},
       "b": {"t": 3}, "t": {}}
print(max_flow(cap, "s", "t"))   # (5, {'s'})

The certificate checks out: the cut around {s}\{s\} has capacity 3+2=53 + 2 = 5, equal to the flow.

7. How the path choice sets the running time

Plain Ford-Fulkerson only promises progress of at least 1 unit per round with integer capacities, so it can take ∣f∗∣\lvert f^*\rvert rounds, and Ford and Fulkerson's own 1962 book gives irrational capacities on which it never terminates and converges to the wrong value. Smarter choices give bounds independent of the capacities.

MethodPath or push ruleRunning timeSource
Ford-Fulkersonany augmenting pathO(∣E∣⋅∣f∗∣)O(\lvert E\rvert \cdot \lvert f^*\rvert), integer capacitiesFord and Fulkerson, 1956
Edmonds-Karpshortest augmenting pathO(∣V∣∣E∣2)O(\lvert V\rvert \lvert E\rvert^2)Edmonds and Karp, 1972
Dinicblocking flow in a BFS layer graphO(∣V∣2∣E∣)O(\lvert V\rvert^2 \lvert E\rvert)Dinic, 1970
Push-relabellocal pushes guided by height labelsO(∣V∣3)O(\lvert V\rvert^3) with FIFO selectionGoldberg and Tarjan, 1988
Interior point with dynamic data structuresminimum-ratio cyclesm1+o(1)m^{1+o(1)}Chen, Kyng, Liu, Peng, Probst Gutenberg, Sachdeva, 2022

The last row settles the asymptotic question for exact max flow on graphs with polynomially bounded integer capacities, in time almost linear in the number of edges mm. It is a theoretical result; practical solvers still use Dinic, push-relabel, or Boykov-Kolmogorov variants.

In practice: NetworkX's maximum_flow defaults to push-relabel (preflow_push), and its documentation warns the default may change between versions, so pass flow_func explicitly when it matters.

8. Integrality: why flows solve combinatorial problems

If every capacity is an integer, augmenting-path algorithms only ever add integer bottlenecks, so they end with an integer flow on every arc. This integrality theorem is what turns max flow into a tool for discrete problems: a fractional answer like "half a person on each shift" never appears.

It also converts each unit of flow into a concrete object. Any integer flow decomposes into at most ∣E∣\lvert E\rvert paths and cycles, so a flow of value kk with unit capacities is literally kk edge-disjoint paths.

Three standard reductions follow:

  • Edge-disjoint paths. Unit capacity on every arc; max flow equals the edge version of Menger.
  • Vertex-disjoint paths. Split each vertex vv into vin→voutv_{\text{in}} \to v_{\text{out}} with capacity 1, route incoming arcs to vinv_{\text{in}} and outgoing arcs from voutv_{\text{out}}. Now a vertex can carry only one path, and max flow equals the vertex version of Menger.
  • Bipartite matching. Source to every left vertex, every right vertex to sink, all capacities 1. Each unit of flow is one matched pair. The next lesson builds on this.

Try it: Model "can 12 delivery vans cover 9 depots, each van reaching only some depots, each depot needing exactly one van?" as a flow network. Which arcs exist, and what flow value means yes?

9. Often the cut is the product

Many applications never look at the flow. They want the minimum cut, because a cut is a partition, and many decisions are partitions.

  • Image segmentation. Greig, Porteous and Seheult (1989, Journal of the Royal Statistical Society) showed that the exact most-probable restoration of a noisy binary image is a minimum cut: each pixel links to ss ("foreground") and tt ("background") with capacities from its colour likelihood, and to its neighbours with a smoothness penalty. Boykov and Jolly (2001) turned this into interactive foreground selection.
  • Project selection. Choose projects with profits and costs, where some projects require others. Picard (1976) showed the most profitable feasible set is the source side of a minimum cut.
  • Elimination. Schwartz (1966) showed that whether a sports team can still finish first, given remaining fixtures, is a max-flow question: the team is out exactly when the remaining games cannot be routed without some rival passing it.

In practice: In segmentation the ss-tt arcs encode "what this pixel looks like" and the neighbour arcs encode "neighbours usually agree". The cut balances the two exactly, with no tuning loop.

10. Modelling moves and traps

Real problems rarely arrive as one source, one sink and directed arcs. Four standard transformations cover most of the gap.

SituationTransformation
Several sources or sinksadd a super-source linked to each source, a super-sink from each sink, with infinite capacity
Undirected edge of capacity cctwo opposite arcs, each of capacity cc
Capacity on a vertexsplit it into in and out copies joined by an arc of that capacity
Lower bounds on arcsshift the bound into vertex demands and solve a feasibility flow first
import networkx as nx
G = nx.DiGraph()
G.add_edge("s", "a", capacity=3); G.add_edge("s", "b", capacity=2)
G.add_edge("a", "b", capacity=1); G.add_edge("a", "t", capacity=2)
G.add_edge("b", "t", capacity=3)
cut_value, (S, T) = nx.minimum_cut(G, "s", "t")
print(cut_value, S)   # 5 {'s', 'a', 'b'}

Gotcha: Minimum cuts are often not unique. The previous step's code returned the side {s}\{s\}; NetworkX returns {s,a,b}\{s, a, b\} for the same network, cutting a→ta \to t and b→tb \to t instead. Both have capacity 5. If the partition itself drives a decision, decide which cut you want (closest to ss, or closest to tt) and compute that one deliberately.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. In the residual graph, what does a backward arc v -> u with residual capacity 4 represent?
    • A physical pipe running from v to u
    • Unused capacity left on the arc u -> v
    • 4 units already sent on u -> v that a later augmenting path may cancel
    • A lower bound of 4 on the flow from v to u
  2. Ford-Fulkerson stops because the sink is unreachable in the residual graph. How do you read off a minimum cut?
    • Take the arcs with the smallest capacities
    • Take S as all vertices reachable from s in the residual graph
    • Take the arcs on the last augmenting path found
    • Take S as the vertices adjacent to t in the original graph
  3. What does Edmonds-Karp change compared to generic Ford-Fulkerson?
    • It always augments along a shortest path found by BFS, giving O(V E^2) time
    • It pushes flow locally using height labels instead of paths
    • It removes backward arcs to save memory
    • It picks the path with the largest bottleneck, giving linear time
  4. You need vertex-disjoint s-t paths, but max flow only limits arcs. What is the standard fix?
    • Give every arc capacity equal to its head vertex's degree
    • Run max flow twice, once in each direction
    • Delete every vertex of degree above 2
    • Split each vertex into an in-copy and an out-copy joined by an arc of capacity 1
  5. Why does max flow with integer capacities reliably solve discrete assignment problems?
    • Because every max flow problem has a unique optimal solution
    • Because augmenting-path algorithms end with an integer flow on every arc
    • Because flows are always bounded by the minimum degree
    • Because the residual graph is always acyclic

Related lessons

Math
intermediate

Graph Connectivity: Bridges, Cut Vertices, and Menger's Theorem

Connected is only the first question; how much damage a graph can absorb is the useful one. Learn vertex and edge connectivity, find every bridge and cut vertex in one depth-first search, and see Menger's theorem turn minimum cuts into a count of disjoint paths.

10 steps·~15 min
Math
advanced

Spectral Graph Theory: What the Laplacian's Eigenvalues Reveal

Turn a graph into its Laplacian matrix and its eigenvalues start answering combinatorial questions: how many components, how many spanning trees, how hard the graph is to cut, and where to cut it. Covers the Fiedler vector, Cheeger's inequality, spectral clustering, random-walk mixing, and expanders.

10 steps·~15 min
Math
intermediate

Matching: Augmenting Paths, Hall, König, and the Assignment Problem

Pair workers with tasks, the most pairs or the cheapest total. Learn why augmenting paths prove a matching is maximum, how Hall's and König's theorems give certificates, how the Hungarian method prices an assignment, and why odd cycles and preferences each change the problem.

10 steps·~15 min
Math
advanced

Newton's method and the interior point revolution

Second derivatives buy something gradients cannot: a step shaped by curvature, immune to conditioning, converging quadratically. This lesson builds Newton's method, then layers it on a log barrier to get interior point methods, the machinery that made large constrained problems solvable with a certificate rather than a hope.

13 steps·~20 min