TExcelTAD
Home › Graph Algorithms › Maximum Bipartite Matching

Maximum Bipartite Matching

Four volunteers and four shifts; each volunteer can work only some of the shifts; each shift needs one person and each person takes at most one shift. How many shifts can be filled? Problems of this shape (applicants and jobs, students and projects, tasks and machines, kidney donors and recipients) are bipartite matching problems. Bipartite Matching in Discrete Mathematics proves Hall's theorem about when everyone can be matched. This lesson finds a maximum matching with a maximum-flow algorithm, and then strips the flow machinery away to get the short augmenting-path algorithm that programmers usually write.

Matchings

A matching in an undirected graph G=(V,E)G = (V, E) is a set M⊆EM \subseteq E of edges no two of which share a vertex. A vertex is matched if some edge of MM touches it, and free otherwise. A maximum matching has the largest possible number of edges. The graph is bipartite if V=L∪RV = L \cup R with every edge between LL and RR; BFS decides whether a graph is bipartite.

The flow network. Direct every edge from LL to RR and give it capacity 1. Add a source ss with an edge of capacity 1 to every vertex of LL, and a sink tt with an edge of capacity 1 from every vertex of RR.

Theorem. The size of a maximum matching in GG equals the value of a maximum flow in this network.

Proof

Matching to flow. Given a matching MM, send one unit along s→u→v→ts \to u \to v \to t for each edge (u,v)∈M(u, v) \in M. Since no vertex is in two edges of MM, every edge of capacity 1 carries at most one unit and conservation holds: a flow of value ∣M∣\lvert M \rvert.

Flow to matching. By the integrality theorem there is a maximum flow ff with integer values, so every edge carries 0 or 1. Let MM be the edges from LL to RR that carry 1. A vertex u∈Lu \in L receives at most 1 unit from ss, so by conservation at most one of its edges carries flow; the same holds for v∈Rv \in R with its single edge to tt. So MM is a matching, and the net flow across the cut ({s}∪L,R∪{t})(\{s\} \cup L, R \cup \{t\}) is ∣M∣=∣f∣\lvert M \rvert = \lvert f \rvert.

Running time. The maximum flow is at most min⁡(∣L∣,∣R∣)≤V/2\min(\lvert L \rvert, \lvert R \rvert) \le V/2, so Ford-Fulkerson needs at most V/2V/2 augmentations of O(E)O(E) each: O(VE)O(VE). The Hopcroft-Karp algorithm augments along many shortest paths at once and achieves O(EV)O(E \sqrt{V}).

Watching it work

Volunteers A,B,C,DA, B, C, D and shifts W,X,Y,ZW, X, Y, Z: AA can take WW or XX, BB only WW, CC either XX or YY, DD either YY or ZZ. Edmonds-Karp matches AA-WW, CC-XX and DD-YY with short paths. Then BB is left out, and the fourth augmenting path rearranges everything: BB takes WW from AA, AA takes XX from CC, CC takes YY from DD, and DD moves to ZZ.

python · try it yourself
from collections import deque

L, R = "ABCD", "WXYZ"
can = {"A": "WX", "B": "W", "C": "XY", "D": "YZ"}
cap = {("S", u): 1 for u in L} | {(u, v): 1 for u in L for v in can[u]} | {(v, "T"): 1 for v in R}
flow = {e: 0 for e in cap}

def bfs(s, t):
    prev, q = {s: None}, deque([s])
    while q and t not in prev:
        u = q.popleft()
        nbrs = [(b, 0) for (a, b) in cap if a == u and flow[(a, b)] < cap[(a, b)]] + \
               [(a, 1) for (a, b) in cap if b == u and flow[(a, b)] > 0]
        for v, back in sorted(nbrs):
            if v not in prev:
                prev[v] = (u, back); q.append(v)
    return prev

while "T" in (prev := bfs("S", "T")):
    path, v = ["T"], "T"
    while prev[v]:
        u, back = prev[v]
        if back: flow[(v, u)] -= 1
        else: flow[(u, v)] += 1
        path.append(u); v = u
    print("augmenting path:", " ".join(reversed(path)))

matching = sorted(f"{u}-{v}" for (u, v), x in flow.items() if x and u in L and v in R)
print("maximum matching:", matching)
augmenting path: S A W T
augmenting path: S C X T
augmenting path: S D Y T
augmenting path: S B W A X C Y D Z T
maximum matching: ['A-X', 'B-W', 'C-Y', 'D-Z']

Augmenting paths without the network

Read the fourth path above inside the bipartite graph itself: B→WB \to W (not in the matching), W→AW \to A (in it, used backwards), A→XA \to X (not in it), X→CX \to C (in it), and so on, ending at the free vertex ZZ. It alternates between non-matching and matching edges and joins two free vertices. Swapping the edges along such an augmenting path grows the matching by one, and Berge's theorem says a matching is maximum exactly when no augmenting path exists. A DFS from each free left vertex finds one: try every neighbour vv; if vv is free, take it; otherwise try to re-match vv's partner elsewhere, recursively. That is Kuhn's algorithm, O(VE)O(VE). The program compares it with the flow version on random bipartite graphs.

python · try it yourself
import random
from collections import deque

def kuhn(left, adj):
    match_r = {}
    def try_assign(u, seen):
        for v in adj[u]:
            if v in seen:
                continue
            seen.add(v)
            if v not in match_r or try_assign(match_r[v], seen):
                match_r[v] = u
                return True
        return False
    return sum(try_assign(u, set()) for u in left), match_r

def flow_matching(left, right, adj):
    cap = {("s", ("L", u)): 1 for u in left}
    cap |= {(("L", u), ("R", v)): 1 for u in left for v in adj[u]}
    cap |= {(("R", v), "t"): 1 for v in right}
    out = {}
    for (a, b) in cap:
        out.setdefault(a, []).append((a, b)); out.setdefault(b, []).append((a, b))
    flow = dict.fromkeys(cap, 0)
    value = 0
    while True:
        prev, q = {"s": None}, deque(["s"])
        while q and "t" not in prev:
            u = q.popleft()
            for (a, b) in out[u]:
                if a == u and flow[(a, b)] == 0 and b not in prev:
                    prev[b] = (a, b); q.append(b)
                elif b == u and flow[(a, b)] == 1 and a not in prev:
                    prev[a] = (a, b); q.append(a)
        if "t" not in prev:
            return value
        v = "t"
        while v != "s":
            a, b = prev[v]
            if b == v: flow[(a, b)] = 1; v = a
            else: flow[(a, b)] = 0; v = b
        value += 1

rng = random.Random(44)
sizes = []
for trial in range(200):
    nl, nr = rng.randint(1, 12), rng.randint(1, 12)
    adj = {u: [v for v in range(nr) if rng.random() < 0.2] for u in range(nl)}
    k, match_r = kuhn(range(nl), adj)
    assert k == flow_matching(range(nl), range(nr), adj)
    assert len(set(match_r.values())) == len(match_r) == k        # a valid matching
    sizes.append(k)
print("Kuhn's algorithm and max flow agree on 200 random bipartite graphs")
print(f"matching sizes from {min(sizes)} to {max(sizes)}, average {sum(sizes) / len(sizes):.2f}")
Kuhn's algorithm and max flow agree on 200 random bipartite graphs
matching sizes from 0 to 11, average 3.85

The practice problem Maximum Bipartite Matching asks for the size of a maximum matching.

In C++

Kuhn's algorithm in C++ is a dozen lines. It solves the volunteer problem.

cpp · try it yourself
#include <cstdio>
#include <functional>
#include <string>
#include <vector>

int main() {
    const std::string left = "ABCD", right = "WXYZ";
    std::vector<std::vector<int>> adj = {{0, 1}, {0}, {1, 2}, {2, 3}};      // A: W X, B: W, C: X Y, D: Y Z
    std::vector<int> match_r(right.size(), -1);
    std::vector<bool> seen;
    std::function<bool(int)> try_assign = [&](int u) {
        for (int v : adj[u]) {
            if (seen[v]) continue;
            seen[v] = true;
            if (match_r[v] < 0 || try_assign(match_r[v])) { match_r[v] = u; return true; }
        }
        return false;
    };
    int size = 0;
    for (int u = 0; u < static_cast<int>(left.size()); ++u) {
        seen.assign(right.size(), false);
        if (try_assign(u)) ++size;
    }
    std::printf("maximum matching has %d edges:", size);
    for (int v = 0; v < static_cast<int>(right.size()); ++v)
        if (match_r[v] >= 0) std::printf(" %c-%c", left[match_r[v]], right[v]);
    std::printf("\n");
}
maximum matching has 4 edges: B-W A-X C-Y D-Z

Test yourself

In the flow network for bipartite matching, what capacity do the edges get?

  1. The degree of the vertex
  2. 1 on every edge
  3. ∞\infty on the middle edges
  4. The number of vertices

Why does Ford-Fulkerson find a maximum bipartite matching in O(VE)O(VE) time?

  1. Because BFS is linear
  2. Because the maximum flow is at most V/2V/2, so there are at most V/2V/2 augmentations of O(E)O(E) each
  3. Because matchings are unique
  4. Because the graph is acyclic

What is an augmenting path for a matching MM?

  1. Any path between two vertices of LL
  2. A path between two free vertices whose edges alternate between non-matching and matching edges
  3. A path of matching edges only
  4. A cycle of even length