Lesson 19 · Problem-solving methods

Network Flow and Maximum Flow

The maximum flow problem asks how much can travel from a source to a sink when every edge has a capacity. Ford–Fulkerson keeps pushing flow along paths in the residual graph, whose reverse edges let it undo earlier choices; when no path is left, a minimum cut proves the answer.

Network Flow and Maximum Flow concept diagramA visual explanation of the layout and operations shown in this lesson.augment along a path, then leave a reverse edge to undo itSABT3/32/43/32/2residual 3S→A→T carries 3S→B→T carries 2no augmenting path leftmax flow = 5the reverse edge is what lets a later path cancel an earlier wrong choice
1

The Maximum Flow Problem

A flow network is a directed graph with a source s, a sink t and a capacity c(u, v) on each edge. A flow assigns each edge an amount f with 0 ≤ f ≤ c, and every vertex other than s and t passes on exactly what it receives (conservation). The maximum flow problem asks for the largest total that can leave s, which equals what arrives at t.

Think of water pipes, network bandwidth or lanes of traffic. Unlike a shortest path, max flow splits across many routes at once. The tracer's network (S→A 3, S→B 2, A→B 2, A→T 2, B→T 3) carries at most 5.

  • 0 ≤ flow ≤ capacity on every edge
  • In = out at every inner vertex
2

Residual Graph and Augmenting Paths

Pushing flow along any path with spare room is the natural idea, but it can get stuck. In the tracer, the first path S → A → B → T fills A → B, two more paths reach 4, and then no path has room left even though 5 is possible.

The residual graph fixes this. For each edge u → v with flow f, it holds a forward edge with spare capacity c − f and a reverse edge v → u with capacity f. Using a reverse edge cancels flow sent earlier: in the tracer, S → B → A → T takes one unit off A → B and sends it on to T instead. An augmenting path is any s-to-t path in the residual graph; its smallest residual capacity, the bottleneck, is how much it can add.

  • Forward residual c − f: room to add
  • Reverse residual f: room to cancel
3

Ford–Fulkerson Algorithm

  1. Start with zero flow on every edge
  2. Find any path from s to t in the residual graph
  3. Take its bottleneck b, the smallest residual capacity on the path
  4. Add b on forward edges and subtract b from the paired reverse edges
  5. Repeat until no residual path exists; the total pushed is the max flow

The Ford–Fulkerson algorithm (1956) is really a method: it does not say how to find the path. With integer capacities each round adds at least 1, so it stops after at most F rounds, where F is the max flow value, and costs O(E · F) with DFS. That bound depends on the capacities: in the tracer's last step, unlucky choices on a network with capacities of 100 take 200 rounds where 2 would do. With irrational capacities it may never stop.

  • O(E · F) with integer capacities
  • Integer capacities give an integer max flow
Key reference

Terms, operations, and practical uses

Flow model

  • CapacityThe most an edge can carry, c(u, v). Flow on the edge stays between 0 and c.
  • ConservationAt every vertex except s and t, total flow in equals total flow out.
  • Flow valueNet flow leaving s, which equals net flow entering t.

Residual graph

  • Residual capacityc − f forward (room to add) and f on the reverse edge (room to cancel).
  • Augmenting pathAn s-to-t path in the residual graph; it can add its bottleneck to the flow.
  • BottleneckThe smallest residual capacity on a path, the amount one round can push.

Optimality

  • s-t cutA split of the vertices with s on one side and t on the other; capacity = edges crossing from s's side.
  • Min cutThe cut of smallest capacity; it equals the max flow.
  • CertificateVertices reachable from s in the final residual graph define a cut equal to the flow.
Implementation

Code in Python, C++ and Java

from collections import deque


def max_flow(cap, s, t, names):
    n = len(cap)
    res = [row[:] for row in cap]
    total = 0
    while True:
        parent = [-1] * n
        parent[s] = s
        q = deque([s])
        while q and parent[t] == -1:
            u = q.popleft()
            for v in range(n):
                if parent[v] == -1 and res[u][v] > 0:
                    parent[v] = u
                    q.append(v)
        if parent[t] == -1:
            return total
        path, v = [t], t
        while v != s:
            v = parent[v]
            path.append(v)
        path.reverse()
        push = min(res[path[i]][path[i + 1]] for i in range(len(path) - 1))
        for i in range(len(path) - 1):
            u, v = path[i], path[i + 1]
            res[u][v] -= push
            res[v][u] += push
        total += push
        print("Augment", "->".join(names[x] for x in path), "by", push)


names = ["S", "A", "B", "T"]
cap = [
    [0, 3, 2, 0],
    [0, 0, 2, 2],
    [0, 0, 0, 3],
    [0, 0, 0, 0],
]
flow = max_flow(cap, 0, 3, names)
print("Max flow:", flow)
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;

int maxFlow(vector<vector<int>> res, int s, int t, const vector<string>& names) {
    int n = res.size(), total = 0;
    while (true) {
        vector<int> parent(n, -1);
        parent[s] = s;
        queue<int> q;
        q.push(s);
        while (!q.empty() && parent[t] == -1) {
            int u = q.front();
            q.pop();
            for (int v = 0; v < n; v++)
                if (parent[v] == -1 && res[u][v] > 0) {
                    parent[v] = u;
                    q.push(v);
                }
        }
        if (parent[t] == -1) return total;
        vector<int> path = {t};
        for (int v = t; v != s; v = parent[v]) path.push_back(parent[v]);
        reverse(path.begin(), path.end());
        int push = INT32_MAX;
        for (size_t i = 0; i + 1 < path.size(); i++) push = min(push, res[path[i]][path[i + 1]]);
        for (size_t i = 0; i + 1 < path.size(); i++) {
            res[path[i]][path[i + 1]] -= push;
            res[path[i + 1]][path[i]] += push;
        }
        total += push;
        cout << "Augment ";
        for (size_t i = 0; i < path.size(); i++) cout << (i ? "->" : "") << names[path[i]];
        cout << " by " << push << "\n";
    }
}

int main() {
    vector<string> names = {"S", "A", "B", "T"};
    vector<vector<int>> cap = {
        {0, 3, 2, 0},
        {0, 0, 2, 2},
        {0, 0, 0, 3},
        {0, 0, 0, 0},
    };
    int flow = maxFlow(cap, 0, 3, names);
    cout << "Max flow: " << flow << "\n";
}
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
    static int maxFlow(int[][] cap, int s, int t, String[] names) {
        int n = cap.length, total = 0;
        int[][] res = new int[n][];
        for (int i = 0; i < n; i++) res[i] = cap[i].clone();
        while (true) {
            int[] parent = new int[n];
            Arrays.fill(parent, -1);
            parent[s] = s;
            ArrayDeque<Integer> q = new ArrayDeque<>();
            q.add(s);
            while (!q.isEmpty() && parent[t] == -1) {
                int u = q.poll();
                for (int v = 0; v < n; v++)
                    if (parent[v] == -1 && res[u][v] > 0) {
                        parent[v] = u;
                        q.add(v);
                    }
            }
            if (parent[t] == -1) return total;
            List<Integer> path = new ArrayList<>();
            path.add(t);
            for (int v = t; v != s; v = parent[v]) path.add(parent[v]);
            Collections.reverse(path);
            int push = Integer.MAX_VALUE;
            for (int i = 0; i + 1 < path.size(); i++) push = Math.min(push, res[path.get(i)][path.get(i + 1)]);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i + 1 < path.size(); i++) {
                res[path.get(i)][path.get(i + 1)] -= push;
                res[path.get(i + 1)][path.get(i)] += push;
            }
            for (int i = 0; i < path.size(); i++) sb.append(i > 0 ? "->" : "").append(names[path.get(i)]);
            total += push;
            System.out.println("Augment " + sb + " by " + push);
        }
    }

    public static void main(String[] args) {
        String[] names = {"S", "A", "B", "T"};
        int[][] cap = {
            {0, 3, 2, 0},
            {0, 0, 2, 2},
            {0, 0, 0, 3},
            {0, 0, 0, 0},
        };
        int flow = maxFlow(cap, 0, 3, names);
        System.out.println("Max flow: " + flow);
    }
}
Watch it run

Step through it

Running on S→A 3, S→B 2, A→B 2, A→T 2, B→T 3

max flow from S to T0/30/20/20/20/3SABTedge label: flow / capacityin = out at A and Bflow value = what leaves Sflow 0
Step 1

A network with capacities

Each edge can carry at most its capacity per second, like pipes from S (source) to T (sink). Every vertex except S and T must pass on exactly what it receives: this is flow conservation. The question is how much can travel from S to T at once. Labels read flow/capacity, and nothing flows yet.

Output
1 / 11
4

Edmonds–Karp Algorithm

The Edmonds–Karp algorithm (1972) is Ford–Fulkerson with one rule: always augment along the path with the fewest edges, found by BFS. Shortest-path distances in the residual graph never decrease, and each edge can be the bottleneck only O(V) times, so there are O(VE) rounds of O(E) each: O(VE²), whatever the capacities.

On the tracer's network BFS finds S → A → T (+2), S → B → T (+2) and S → A → B → T (+1). For large graphs, Dinic's algorithm (O(V²E), much faster in practice and O(E√V) on unit-capacity bipartite graphs) and push–relabel are the usual choices.

Max flow algorithms compared
AlgorithmPath choiceTimeUse
Ford–FulkersonAny path (DFS)O(E · F)Small integer capacities
Edmonds–KarpShortest path (BFS)O(VE²)Interviews, moderate graphs
DinicBlocking flow on BFS levelsO(V²E)Contests, bipartite matching
Push–relabelLocal pushes, no pathsO(V²√E) with FIFO/highest-labelVery large dense graphs
  • BFS removes the dependence on F
  • Dinic for large inputs
5

Max Flow Min Cut Theorem

An s-t cut splits the vertices into a set S containing s and the rest containing t; its capacity is the total capacity of edges from S to the rest. Every unit of flow must cross the cut, so no flow can exceed any cut's capacity.

When Ford–Fulkerson stops, let S be the vertices still reachable from s in the residual graph. Every edge leaving S is full and every edge entering S is empty, so the flow equals that cut's capacity. This is the max flow min cut theorem: the largest flow equals the smallest cut, and the final residual search hands you both. In the tracer only S is reachable at the end, and the cut S → A 3 + S → B 2 = 5 matches the flow.

  • Any flow ≤ any cut
  • At the end: flow = cut, both optimal
6

Modelling Problems as Flow

Bipartite matching: source → each left vertex (capacity 1), left → right for allowed pairs (1), right → sink (1); the max flow is the size of the largest matching (bipartite graphs). Disjoint paths: unit capacities count edge-disjoint routes. Several sources or sinks: add a super-source and super-sink. Vertex capacities: split a vertex into v_in → v_out with that capacity.

Min cut is just as useful: the cheapest set of edges whose removal disconnects s from t, as in image segmentation or project selection. Costs per unit (min-cost flow) and lower bounds on edges need extensions beyond plain max flow. Related: breadth-first search, graph algorithms.

  • Matching = unit-capacity flow
  • Cut = cheapest separation
7

Implementation Notes and Bugs

Store each edge with the index of its reverse so an update touches both in O(1); an adjacency matrix (as in the code here) is fine for small V. Forgetting the reverse edge gives the greedy answer, 4 instead of 5 in the tracer. Antiparallel edges (u → v and v → u both in the input) must stay separate from each other's reverse edges, or capacities get merged by mistake. Use 64-bit totals when capacities are large.

Test a graph with no s-t path (flow 0), a case that needs a reverse edge, parallel edges, and zero-capacity edges. After the run, assert conservation at every inner vertex and that the reachable set's cut equals the flow; a correct-looking total can hide illegal edge flows.

  • Pair every edge with its reverse
  • Check conservation and the cut