Matching and Augmenting Paths
Let $G=(L\cup R,E)$ be bipartite: every edge joins a left vertex to a right vertex. A matching $M$ is a set of edges with no shared endpoint. Its size $|M|$ counts how many left–right pairs have been formed, and a maximum matching has the largest possible size.
Matched edge
An edge currently chosen in $M$. Each vertex touches at most one such edge.
Free vertex
A vertex with no current partner. Augmenting paths begin and end free.
Alternating path
A path whose edges alternate between outside and inside the matching.
An augmenting path starts at a free left vertex, ends at a free right vertex, and alternates unmatched–matched–unmatched edges. It contains one more unmatched edge than matched edge. Flipping every edge along the path therefore increases the matching size by exactly one.
where $\triangle$ is symmetric difference: remove path edges already in $M$ and add path edges not in $M$.
Intuition: A Chain of Reassignments
A free applicant wants an occupied role. The current holder can move to another eligible free role, perhaps after several handoffs. Alternation guarantees that every displaced person receives a new assignment, while the initially free applicant becomes matched. Nobody ends with two roles.
Why Flipping an Augmenting Path Works
Berge's Theorem Is the Finish Line
A matching is maximum if and only if no augmenting path exists. Every successful phase grows the matching; a BFS that cannot reach any free right vertex certifies optimality.
One Phase: BFS Layers, Then a DFS Batch
A basic augmenting-path algorithm searches, flips one path, and starts over. Hopcroft–Karp amortizes the search by handling a whole maximal set of vertex-disjoint shortest augmenting paths in one phase.
- Multi-source BFS: begin from every free left vertex at distance zero.
- Build the alternating layered graph: move left-to-right only through unmatched edges, then right-to-left only through the right vertex's current matched edge.
- Stop at the shortest free-right layer: once a free right vertex is reachable, record that augmenting distance and do not build deeper layers.
- Layer-respecting DFS: from each free left vertex, follow only edges that advance exactly one BFS layer and finish at that shortest distance.
- Flip all found paths: the DFS paths are vertex-disjoint, so their updates do not conflict.
What BFS Actually Measures
Most implementations store distances only for left vertices. Crossing an unmatched edge to right vertex $v$ and then its matched edge to left vertex pairV[v] advances one left-layer. A separate distNil records the first level that reaches any free right vertex.
Worked Phase: Two Paths at Once
Suppose the current matching is $M=\{A\!-!1, B\!-!2\}$. Left vertices $C,D$ and right vertices $3,4$ are free. The graph contains the alternating routes $C-1-A-3$ and $D-2-B-4$.
| Stage | State | Meaning |
|---|---|---|
| BFS seed | $C,D$ at left-distance $0$ | Both unmatched left vertices start simultaneously. |
| First alternating step | $C\to1\to A$ and $D\to2\to B$ | Unmatched edge out, matched edge back. |
| Free right reached | $A\to3$ and $B\to4$ | The shortest augmenting length is three edges. |
| DFS batch | Two vertex-disjoint paths | They form a maximal set in this layered graph. |
| Flip | $M'=\{C\!-!1,A\!-!3,D\!-!2,B\!-!4\}$ | Matching size rises from two to four. |
Correctness and the $O(\sqrt{V})$ Phase Bound
Three facts connect the phase mechanics to the final guarantee:
- Every DFS success is a valid augmentation. Layer rules enforce alternation, and vertex-disjoint paths can be flipped together without assigning any vertex twice.
- The shortest augmenting-path length strictly increases after a phase. DFS finds a maximal set that blocks every shortest route in the current layered graph. Any surviving augmenting path must therefore be longer.
- No augmenting path means maximum. This is exactly Berge's theorem.
The phase count uses a short-path/long-path split. During the first $O(\sqrt{V})$ phases, the shortest augmenting length increases at least once per phase. Once that length exceeds $\sqrt{V}$, compare the current matching $M$ with a maximum matching $M^*$. Their symmetric difference decomposes into vertex-disjoint alternating cycles and paths. Every remaining augmenting component is long, so only $O(\sqrt{V})$ such components can fit among $V$ vertices. Hence the deficit $|M^*|-|M|$ is $O(\sqrt{V})$, and at most that many additional phases are possible.
Why “Maximal” Is Enough
The DFS batch need not contain the greatest possible number of disjoint shortest paths. It only needs to be maximal: no additional shortest path can be added without sharing a vertex. That blocking property eliminates every shortest augmenting route and forces the next phase deeper.
Implementation
The code below numbers left vertices $0\ldots |L|-1$ and right vertices $0\ldots |R|-1$. pairU[u] is the right partner of left vertex $u$; pairV[v] is the left partner of right vertex $v$; $-1$ means free. The explicit distNil counts unmatched left-to-right steps on a shortest augmenting route, so its ordinary edge length is $2\cdot\text{distNil}-1$.
Complexity and Alternatives
Within one phase, BFS scans the bipartite edges to build layers. DFS scans admissible edges while failed left vertices are marked unreachable for the rest of that phase. Thus a phase costs $O(E)$, not one full search per augmented path.
Here $V=|L|+|R|$. The space includes adjacency lists, two partner arrays, the BFS distance array, and the queue. For a dense bipartite graph with $|L|=|R|=n$, $V=2n$ and $E$ may be $n^2$; the edge count still dominates the actual scanning work.
| Problem | Typical algorithm | Time | What changes? |
|---|---|---|---|
| Unweighted bipartite maximum matching | Hopcroft–Karp | $O(E\sqrt{V})$ | Best fit for this page's model |
| One augmenting path per search | Kuhn-style DFS | $O(VE)$ worst case | Simpler; often fine for small inputs |
| Bipartite matching as flow | Max-flow reduction | Depends on flow algorithm | Useful when capacities or extra constraints matter |
| Weighted bipartite assignment | Hungarian / min-cost flow | Problem-dependent | Optimizes total weight, not only cardinality |
| General non-bipartite matching | Blossom-family algorithms | Problem-dependent | Must handle odd cycles |
Real-World Applications
Hopcroft–Karp answers a precise question: what is the largest number of compatible left–right pairs when every acceptable pair has equal value?
Eligibility assignment
Match applicants to roles, volunteers to shifts, or students to projects using yes/no compatibility edges.
Resource allocation
Pair jobs with machines that can execute them when every machine and job may be used at most once.
Graph reductions
Use bipartite matching inside minimum vertex cover, path-cover, and scheduling reductions.
Minimum Vertex Cover in Bipartite Graphs
Kőnig's theorem says the maximum matching size equals the minimum vertex-cover size in a bipartite graph. After Hopcroft–Karp finds a maximum matching, one additional alternating reachability search can construct a minimum vertex cover—turning a pairing routine into a certificate for a seemingly different optimization problem.
Pitfalls and Implementation Checklist
Common Failure Modes
- Mixing the partitions: adjacency lists should run from left IDs to right IDs, with separate partner arrays.
- Starting BFS from matched left vertices: only free left vertices can begin augmenting paths.
- Searching below the first free-right layer: deeper paths are not part of the current shortest-path phase and can break the complexity argument.
- Ignoring DFS layer checks: DFS must move from distance $d$ to $d+1$ through the matched partner, and it may finish only at
distNil. - Omitting dead-end pruning: setting
dist[u] = INFafter DFS failure prevents repeated rescans during the phase. - Counting a flip incorrectly: increment matching size once per successful augmenting path, not once per edge changed.
- Using it for weighted preference: maximum cardinality ignores which maximum matching has the best total score.
- Overlooking recursion depth: a very long alternating path may require an iterative DFS or a larger safe stack.
Validate the Output
For every matched $u$, confirm that $(u,\text{pairU}[u])$ is a real edge; verify pair arrays agree in both directions; ensure no partner appears twice; and check that the reported size equals the number of non-free entries. On small random graphs, compare against brute force or a trusted max-flow implementation.
Exercises
- Trace the worked graph from an empty matching. Show that phase one finds $A-1$ and $B-2$, while phase two finds both length-three augmenting paths.
- Remove edge $B-4$. Redraw the layered graph and determine the matching returned after the next phase.
- Explain why two augmenting paths that share a vertex cannot safely be flipped as independent updates.
- Instrument the implementation to print
distNil, the number of successful DFS calls, and matching size after every phase. - Construct the minimum vertex cover from the final matching using alternating reachability.
- Compare Hopcroft–Karp with a one-path-at-a-time DFS matcher on increasingly large sparse graphs.
- Challenge: replace recursive DFS with explicit stack frames while preserving path reconstruction and layer pruning.
Historical Note
John Hopcroft and Richard Karp introduced the algorithm in 1973. Its enduring idea is broader than matching: when many shortest improvements are independent, construct a layered search space once and apply a maximal batch before rebuilding it. That phase-based pattern reappears throughout advanced flow and matching algorithms.
Takeaway
Hopcroft–Karp is not merely “BFS plus DFS.” BFS defines the shortest legal alternating layers; DFS extracts a blocking batch inside exactly those layers; flipping the disjoint paths grows the matching; and the forced increase in shortest-path length limits the number of phases to $O(\sqrt{V})$.