Sub topic 12
A First Look at Bipartite Matching
Earlier chapters showed how to test whether a graph is bipartite and how to split its vertices into two sides. This chapter uses that split for one of the most common jobs bipartite graphs do: pairing things up. This chapter assumes you know the two-colouring algorithms from earlier chapters, depth-first search, and Big-O notation. It is an overview. It covers the central idea, augmenting paths, and one complete algorithm. Faster algorithms and the full proofs belong to a dedicated matching course.
What a Matching Is
A matching is a set of edges where no two edges share a vertex. Each vertex is paired with at most one partner. A vertex that touches an edge of the matching is matched. Any other vertex is free.
In a bipartite graph with sides L and R, every edge joins a vertex in L to a vertex in R. A matching therefore pairs some left vertices with some right vertices, one to one. Typical examples are workers and jobs, students and project slots, or ads and ad slots.
The following terms are easy to mix up:
| Term | Meaning |
|---|---|
| Matching | A set of edges with no shared endpoints |
| Maximal matching | No edge can be added without breaking the matching rule |
| Maximum matching | A matching with the largest possible number of edges |
| Perfect matching | Every vertex in the graph is matched |
| Augmenting path | A path that starts and ends at free vertices and alternates between edges outside and inside the matching |
A perfect matching is always maximum. A maximum matching is always maximal. The reverse does not hold, and the gap between "maximal" and "maximum" is where naive algorithms fail.
Why Greedy Pairing Fails
The obvious approach is to walk through the left vertices and give each one the first free right vertex it is connected to. This approach always produces a maximal matching, but the result can be smaller than the maximum.
Take two workers and two jobs. Worker 0 can do job 0 or job 1. Worker 1 can only do job 0.
| Step | Greedy choice | Matching so far |
|---|---|---|
| Worker 0 | Takes job 0, its first option | {(W0, J0)} |
| Worker 1 | Wants job 0, which is taken; no other option | {(W0, J0)} |
Greedy stops with one pair. The maximum is two pairs: W0 with J1 and W1 with J0. Greedy fails because it never undoes a choice. Worker 0 took the only job worker 1 could do, and nothing later moved worker 0 to job 1.
Augmenting Paths
The fix is to allow reassignments, and augmenting paths make reassignment systematic.
An alternating path uses edges outside the matching and edges inside it in turn. An augmenting path is an alternating path whose two ends are both free. In the example above, after greedy has matched W0 with J0, this path is augmenting:
W1 → J0 → W0 → J1
The edge W1–J0 is outside the matching, J0–W0 is inside it, and W0–J1 is outside it. Both W1 and J1 are free. To augment, flip the status of every edge on the path: edges outside the matching join it, and edges inside it leave. W1–J0 and W0–J1 are now matched and J0–W0 is not. The matching grew by exactly one edge.
Flipping always works. An augmenting path has one more non-matching edge than matching edges, so flipping adds one edge to the total. Each inner vertex of the path loses one partner and gains one, so it stays matched to exactly one vertex. The two free ends each gain a partner. The result is still a valid matching.
The key fact is Berge's theorem: a matching is maximum if and only if no augmenting path exists. This gives a complete algorithm. Start with an empty matching, find an augmenting path, flip it, and repeat. When no augmenting path is left, the matching is maximum.
Where bipartiteness helps
Berge's theorem holds in every graph, but finding augmenting paths is much easier in bipartite graphs. In a two-coloured graph, every edge changes colour, so a path from a free left vertex has odd length exactly when it ends on the right side. A search that leaves left vertices only by non-matching edges and leaves right vertices only by their matching edge cannot get confused.
In a general graph, an odd cycle can let the search reach the same vertex once by an even-length path and once by an odd-length path. The simple search then misses augmenting paths. Handling this needs Edmonds' blossom algorithm, which shrinks odd cycles into single vertices. The odd cycles from earlier chapters are exactly what makes matching hard outside bipartite graphs.
Kuhn's Algorithm
Kuhn's algorithm, also called the Hungarian augmenting-path method in its simplest form, runs one depth-first search from each left vertex in turn. The search tries to find the left vertex a partner. If the right vertex it wants is free, the search takes it. If that right vertex is taken, the search recursively asks the current partner to move to another right vertex. A successful search traces out an augmenting path, and the assignments made as the recursion unwinds flip that path.
def max_matching(n_left, n_right, adj):
"""Maximum bipartite matching by repeated augmenting-path DFS.
adj[u] lists the right vertices adjacent to left vertex u.
Returns (size, match_right) where match_right[v] is the left
partner of right vertex v, or -1 if v is free.
"""
match_right = [-1] * n_right
def try_augment(u, seen):
for v in adj[u]:
if seen[v]:
continue
seen[v] = True
# v is free, or v's current partner can move elsewhere.
if match_right[v] == -1 or try_augment(match_right[v], seen):
match_right[v] = u
return True
return False
size = 0
for u in range(n_left):
if try_augment(u, [False] * n_right):
size += 1
return size, match_right
# Workers 0..2 and jobs 0..2.
# Worker 0 can do jobs 0 or 1, worker 1 only job 0, worker 2 jobs 1 or 2.
adj = [[0, 1], [0], [1, 2]]
size, match_right = max_matching(3, 3, adj)
print(size) # 3
print(match_right) # [1, 0, 2] (job 0 -> worker 1, job 1 -> worker 0, job 2 -> worker 2)Here is how the run unfolds:
| Left vertex | What the search does | Result |
|---|---|---|
| Worker 0 | Job 0 is free | Job 0 → worker 0 |
| Worker 1 | Job 0 is taken; asks worker 0 to move; worker 0 finds job 1 free | Job 1 → worker 0, job 0 → worker 1 |
| Worker 2 | Job 1 is taken; worker 0 cannot move again because jobs 0 and 1 are both seen; tries job 2, which is free | Job 2 → worker 2 |
Worker 1's step is the augmenting path W1 → J0 → W0 → J1 from the previous section, found and flipped by the recursion.
Why the `seen` array matters
The seen array marks right vertices already visited during the current search. Without it, two left vertices could keep asking each other to move and the search would never finish. Each search gets a fresh array because a right vertex that led nowhere for one left vertex might be useful for the next one.
Cost
Each search is a DFS that visits each right vertex at most once and scans each edge at most once, so it costs O(V + E). One search runs per left vertex, which gives O(V · E) overall. That is fast enough for graphs with thousands of vertices. For larger inputs, the Hopcroft–Karp algorithm finds many disjoint shortest augmenting paths in each phase and runs in O(E √V). Matching can also be solved as a maximum-flow problem: add a source joined to every left vertex, a sink joined to every right vertex, and give every edge capacity 1.
Getting the Sides from Two-Colouring
Kuhn's algorithm needs the left and right sides given separately. If you start with an ordinary adjacency list, two-colour the graph first and then number each side on its own. This self-contained example combines the BFS colouring from earlier chapters with max_matching:
from collections import deque
def two_colour(n, adj):
colour = [-1] * n
for start in range(n):
if colour[start] != -1:
continue
colour[start] = 0
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if colour[v] == -1:
colour[v] = 1 - colour[u]
queue.append(v)
elif colour[v] == colour[u]:
return None
return colour
def max_matching(n_left, n_right, adj):
match_right = [-1] * n_right
def try_augment(u, seen):
for v in adj[u]:
if seen[v]:
continue
seen[v] = True
if match_right[v] == -1 or try_augment(match_right[v], seen):
match_right[v] = u
return True
return False
size = sum(try_augment(u, [False] * n_right) for u in range(n_left))
return size, match_right
def matching_from_graph(n, adj):
colour = two_colour(n, adj)
if colour is None:
raise ValueError("graph is not bipartite")
left = [x for x in range(n) if colour[x] == 0]
right = [x for x in range(n) if colour[x] == 1]
index = {x: i for i, x in enumerate(right)}
side_adj = [[index[y] for y in adj[x]] for x in left]
size, match_right = max_matching(len(left), len(right), side_adj)
pairs = [(left[u], right[v]) for v, u in enumerate(match_right) if u != -1]
return size, pairs
# A path 0-1-2-3: the maximum matching has two edges.
path = [[1], [0, 2], [1, 3], [2]]
print(matching_from_graph(4, path)) # (2, [(0, 1), (2, 3)])The renumbering step matters. max_matching indexes match_right by right-side position, not by the original vertex number. Passing original vertex numbers there is a frequent bug that produces index errors or silently wrong pairs.
Two Theorems Worth Knowing
König's theorem. A vertex cover is a set of vertices that touches every edge. In a bipartite graph, the smallest vertex cover has exactly as many vertices as the largest matching. A maximum matching therefore also proves that no smaller cover exists, much as an odd cycle proves that a graph is not bipartite. The theorem fails for general graphs. A triangle has a maximum matching of size 1 but needs 2 vertices to cover its edges.
Hall's theorem. Every left vertex can be matched if and only if every subset S of left vertices has at least |S| neighbours on the right. If some group of three workers can only do two jobs between them, no assignment can cover all three. Kuhn's algorithm finds such a group when it fails: it is the set of left vertices the last failed search reached.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Running Kuhn's algorithm on a non-bipartite graph | Matching smaller than the maximum, with no error | Two-colour first and reject graphs with odd cycles, or use the blossom algorithm |
| Using one `seen` array for all left vertices | Later left vertices fail to augment | Create a fresh array for each outer search |
| Mixing original vertex numbers and side indices | Index errors or wrong pairs | Renumber each side from 0 before matching |
| Trusting greedy results | Maximal but not maximum matching | Keep searching for augmenting paths until none remain |
Exercise
Left vertices A, B, C and right vertices 1, 2, 3 have edges A–1, A–2, B–1, C–1. What is the maximum matching size, and which subset of left vertices shows, by Hall's theorem, that a perfect matching is impossible?
Show answer
The maximum is 2, for example A–2 and B–1. The subset {B, C} has only one neighbour, vertex 1, which is fewer than its two members, so B and C cannot both be matched.
Exercise
In a bipartite graph, explain why an augmenting path always has odd length.
Show answer
Its two ends are free vertices on opposite sides, one in L and one in R. Every edge changes sides, so a path from L to R has an odd number of edges. Equivalently, the path alternates and begins and ends with a non-matching edge, so it has k matching edges and k + 1 non-matching edges, 2k + 1 in total.
Exercise
Run max_matching(2, 2, [[0], [0, 1]]) by hand. What does it return, and does the second search need to reassign anyone?
Show answer
Left 0 takes right 0. Left 1 tries right 0, which is taken, so it asks left 0 to move. Left 0 has no other option, so that attempt fails. Left 1 then takes right 1, which is free. The call returns (2, [0, 1]). The reassignment attempt failed and was not needed, because left 1 had a free alternative.