Sub topic 12
A First Look at Bipartite Matching
This chapter assumes you can read recursive Python, know what an adjacency list is, and have met the two-colouring code from earlier chapters. You don't need any prior knowledge of matching.
The problem
A matching is a set of edges where no two edges share a vertex. Each vertex is paired with at most one partner. A maximum matching is a matching with as many edges as possible.
Matching is easiest to think about on bipartite graphs, because the two sides often stand for two kinds of thing: workers and jobs, students and project slots, or doctors and shifts. An edge means "this pair is allowed." The question is how many pairs you can form at once.
You need to know which side each vertex is on before a matching algorithm can start. If your input is just a graph, run the two-colouring from earlier chapters first. Colour 0 is the left side and colour 1 is the right side. If two-colouring fails, the graph is not bipartite, and the algorithm below does not apply.
Augmenting paths
A greedy approach pairs each worker with the first free job it finds. That can get stuck. Suppose worker 0 takes job 0, and then worker 1 can only do job 0. Greedy stops there, but worker 0 could have taken job 1 and left job 0 for worker 1.
The fix is an augmenting path. This is a path that starts at an unmatched left vertex, ends at an unmatched right vertex, and alternates between edges outside the matching and edges inside it. If you flip every edge on the path, so matched edges become unmatched and the reverse, the matching grows by one. Berge's theorem says a matching is maximum exactly when no augmenting path exists. The algorithm therefore keeps searching for augmenting paths until it can't find one.
Kuhn's algorithm
Kuhn's algorithm runs a depth-first search from each left vertex in turn. When it reaches a right vertex that is already taken, it tries to move that vertex's current partner somewhere else.
def max_matching(left_n, right_n, adj):
"""adj[u] lists right vertices allowed for left vertex u.
Returns (size, match_right) where match_right[v] is v's partner or -1."""
match_right = [-1] * right_n
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(left_n):
if try_augment(u, [False] * right_n):
size += 1
return size, match_right
# Workers 0..2, jobs 0..2. Worker 1 can only do job 0.
adj = [[0, 1], [0], [1, 2]]
print(max_matching(3, 3, adj)) # (3, [1, 0, 2])Here is how the example runs:
- Worker 0 takes job 0.
- Worker 1 asks for job 0. The search sends worker 0 to job 1, and worker 1 gets job 0.
- Worker 2 tries job 1, but no one can be displaced, so it takes job 2.
Cost and alternatives
Each call to try_augment visits every edge at most once, because of seen. The algorithm makes one call per left vertex, so it runs in O(V · E) time. That is fast enough for graphs with a few thousand vertices.
| Algorithm | Time | When to use |
|---|---|---|
| Kuhn's (above) | O(V · E) | Small to medium inputs, short code |
| Hopcroft–Karp | O(E √V) | Large sparse graphs |
| Max-flow reduction | Depends on flow algorithm | You already have a flow library |
| Hungarian algorithm | O(V³) | Edges have costs and you want the cheapest perfect matching |
König's theorem gives a useful extra fact. In a bipartite graph, the size of a maximum matching equals the size of a minimum vertex cover. A minimum vertex cover is the smallest set of vertices that touches every edge. This equality fails for general graphs, which is one more reason bipartite structure is worth detecting.
Exercise
Run max_matching(2, 2, [[0], [0]]) by hand. What does it return, and why can't the matching have size 2?
Show answer
It returns (1, [0, -1]). Both workers can only do job 0. Worker 0 takes it. Worker 1's search finds job 0 taken and tries to move worker 0, but worker 0 has no other job. No augmenting path exists, so the matching stays at size 1. Job 1 has no edges at all, so it can never be matched.
Exercise
A graph is given without sides marked. What should you do before calling max_matching, and what does it mean if that step fails?
Show answer
Run two-colouring to split the vertices into left (colour 0) and right (colour 1). Then renumber each side from 0 and build adj from the left side only. If two-colouring returns None, the graph has an odd cycle and is not bipartite. Kuhn's algorithm does not apply, and you need a general matching algorithm such as Edmonds' blossom algorithm.