Skip to lesson

Maximum flow and matching (overview)

Flow networks model throughput limits and solve maximum bipartite matching problems via augmenting paths.

Networks, capacities, and the flow conservation rule

A flow network is a directed graph where each edge has a non-negative capacity c(u, v). Material originates at a designated source vertex S and terminates at a sink vertex T. Valid flow must strictly satisfy two fundamental physical laws.

Java
int[][] cap = new int[4][4];     // cap[u][v] = capacity left on edge u -> vcap[0][1] = 10; cap[0][2] = 5;   // source S = 0cap[1][2] = 6;cap[1][3] = 4;  cap[2][3] = 8;   // sink T = 3// Pushing f units along u -> v uses up capacity// and adds an "undo" edge v -> u that a later path can cancelint u = 0, v = 1, f = 4;cap[u][v] -= f;cap[v][u] += f;

First, the capacity constraint dictates that flow on any edge cannot exceed its capacity. Second, the flow conservation rule requires that total inflow equals total outflow for all intermediate nodes. Only source S generates net outflow, and only sink T absorbs net inflow.

Brute force greedy approaches push flow along arbitrary paths until no paths remain. However, premature greedy decisions can block globally superior alternate routings. To achieve true maximum flow, algorithms must incorporate an undo mechanism.

Augmenting paths, residual graphs, and Edmonds-Karp

The residual graph models available capacity and enables flow rerouting. A forward edge carries remaining capacity equal to c(u, v) - f(u, v). A backward edge carries capacity equal to f(u, v), allowing earlier flow decisions to be undone.

Example 1 · Edmonds-Karp Maximum Flow Implementation

EdmondsKarpDemo.javaJava
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Queue;
public class EdmondsKarpDemo {    public static int maxFlow(int n, int[][] capacity, int src, int sink) {        int[][] flow = new int[n][n];        int totalFlow = 0;
        while (true) {            int[] parent = new int[n];            Arrays.fill(parent, -1);            parent[src] = src;
            Queue<Integer> q = new ArrayDeque<>();            q.offer(src);
            while (!q.isEmpty() && parent[sink] == -1) {                int u = q.poll();                for (int v = 0; v < n; v++) {                    if (parent[v] == -1 && capacity[u][v] - flow[u][v] > 0) {                        parent[v] = u;                        q.offer(v);                    }                }            }
            if (parent[sink] == -1) break; // No augmenting path
            int push = Integer.MAX_VALUE;            for (int curr = sink; curr != src; curr = parent[curr]) {                int prev = parent[curr];                push = Math.min(push, capacity[prev][curr] - flow[prev][curr]);            }
            for (int curr = sink; curr != src; curr = parent[curr]) {                int prev = parent[curr];                flow[prev][curr] += push;                flow[curr][prev] -= push; // Residual backward edge            }            totalFlow += push;        }        return totalFlow;    }
    public static void main(String[] args) {        int n = 4;        int[][] cap = new int[n][n];        // 0: Source, 3: Sink        cap[0][1] = 3;        cap[0][2] = 2;        cap[1][2] = 1;        cap[1][3] = 2;        cap[2][3] = 3;
        int flow = maxFlow(n, cap, 0, 3);        System.out.println("Maximum flow: " + flow);    }}
Output
Maximum flow: 5

What this code does

  • Uses BFS to discover the shortest augmenting path in the residual capacity graph.
  • Updates forward flow and negative backward residual capacity along the chosen path.
  • Reaches maximum throughput of 5 units from source 0 to sink 3.

An augmenting path is any simple path from S to T in the residual graph with positive capacity. Pushing the bottleneck capacity along this path increases total net flow. Ford-Fulkerson chooses arbitrary augmenting paths, which can take O(E * max_flow) time. Edmonds-Karp improves this by using breadth-first search to select the shortest augmenting path. Choosing paths with the fewest edges bounds the total augmentations to O(V * E). This guarantees a strongly polynomial runtime of O(V * E^2), independent of edge capacities.

Order of execution

Run Edmonds-Karp

Tap the steps of Edmonds-Karp in the order they run.

The Max-Flow Min-Cut theorem and bipartite matching

An S-T cut partitions vertices into two disjoint sets, A containing S and B containing T. The cut capacity is the sum of capacities of all edges directed from set A to set B.

The Max-Flow Min-Cut Theorem proves that maximum flow equals the minimum capacity of any S-T cut.

Example 2 · Minimum Cut Identification

MinCutDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.Queue;
public class MinCutDemo {    public static List<String> findMinCutEdges(int n, int[][] cap, int[][] flow, int src) {        boolean[] reachable = new boolean[n];        Queue<Integer> q = new ArrayDeque<>();        q.offer(src);        reachable[src] = true;
        while (!q.isEmpty()) {            int u = q.poll();            for (int v = 0; v < n; v++) {                if (!reachable[v] && cap[u][v] - flow[u][v] > 0) {                    reachable[v] = true;                    q.offer(v);                }            }        }
        List<String> cutEdges = new ArrayList<>();        for (int u = 0; u < n; u++) {            if (reachable[u]) {                for (int v = 0; v < n; v++) {                    if (!reachable[v] && cap[u][v] > 0) {                        cutEdges.add(u + "->" + v);                    }                }            }        }        return cutEdges;    }
    public static void main(String[] args) {        int n = 4;        int[][] cap = {{0, 3, 2, 0}, {0, 0, 1, 2}, {0, 0, 0, 3}, {0, 0, 0, 0}};        int[][] flow = {{0, 3, 2, 0}, {0, 0, 1, 2}, {0, 0, 0, 3}, {0, 0, 0, 0}};
        List<String> cut = findMinCutEdges(n, cap, flow, 0);        System.out.println("Min-cut edges: " + cut);    }}
Output
Min-cut edges: [0->1, 0->2]

What this code does

  • Runs BFS on the residual graph to find all vertices reachable from the source.
  • Identifies saturated edges crossing from the reachable set to the unreachable set.
  • Identifies edges 0->1 and 0->2 having total capacity 3 + 2 = 5, matching the maximum flow.

Example 3 · Maximum Bipartite Matching via Flow Reduction

BipartiteMatchingDemo.javaJava
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Queue;
public class BipartiteMatchingDemo {    private static int bfsMaxFlow(int n, int[][] cap, int src, int sink) {        int[][] flow = new int[n][n];        int total = 0;        while (true) {            int[] parent = new int[n];            Arrays.fill(parent, -1);            parent[src] = src;            Queue<Integer> q = new ArrayDeque<>();            q.offer(src);            while (!q.isEmpty() && parent[sink] == -1) {                int u = q.poll();                for (int v = 0; v < n; v++) {                    if (parent[v] == -1 && cap[u][v] - flow[u][v] > 0) {                        parent[v] = u;                        q.offer(v);                    }                }            }            if (parent[sink] == -1) break;            int push = Integer.MAX_VALUE;            for (int c = sink; c != src; c = parent[c]) {                push = Math.min(push, cap[parent[c]][c] - flow[parent[c]][c]);            }            for (int c = sink; c != src; c = parent[c]) {                flow[parent[c]][c] += push;                flow[c][parent[c]] -= push;            }            total += push;        }        return total;    }
    public static int maxBipartiteMatching(boolean[][] matches, int numApplicants, int numJobs) {        int totalNodes = numApplicants + numJobs + 2;        int src = 0;        int sink = totalNodes - 1;        int[][] cap = new int[totalNodes][totalNodes];
        for (int i = 0; i < numApplicants; i++) {            cap[src][i + 1] = 1; // S -> applicant        }        for (int j = 0; j < numJobs; j++) {            cap[numApplicants + 1 + j][sink] = 1; // job -> T        }        for (int i = 0; i < numApplicants; i++) {            for (int j = 0; j < numJobs; j++) {                if (matches[i][j]) {                    cap[i + 1][numApplicants + 1 + j] = 1;                }            }        }
        return bfsMaxFlow(totalNodes, cap, src, sink);    }
    public static void main(String[] args) {        // 3 applicants, 3 jobs        boolean[][] match = {            {true, true, false},            {false, true, true},            {false, false, true}        };        int matched = maxBipartiteMatching(match, 3, 3);        System.out.println("Maximum matched pairs: " + matched);    }}
Output
Maximum matched pairs: 3

What this code does

  • Creates super-source with capacity 1 to all applicants and super-sink from all jobs.
  • Inserts capacity 1 directed edges representing applicant job eligibilities.
  • Finds that all 3 applicants can be successfully matched to distinct jobs.

Maximum Bipartite Matching models assignment problems, such as matching job applicants to jobs. Create a super-source S connected to all applicants with capacity 1. Connect applicants to eligible jobs with capacity 1. Connect all jobs to a super-sink T with capacity 1.

Running maximum flow on this network finds the maximum number of matched pairs in O(V * E) time. Integral capacities guarantee that flow on every edge is either 0 or 1. This reduction cleanly maps assignment challenges to network flow solutions.

Next step

Check your understanding

10 quick questions