TExcelTAD
Home › Discrete Mathematics › Bipartite Graphs and Matching

Bipartite Graphs and Matching

A graph is bipartite if its vertices split into two sides LL and RR so that every edge goes between the sides. Applicants and jobs, students and project slots, ads and ad slots, doctors and hospitals: assignment problems are bipartite graphs, and a solution is a matching. This lesson proves Hall's theorem, which says exactly when everyone can be matched, and shows the stable matching algorithm used for residency placements.

Bipartite graphs

Theorem. A graph is bipartite if and only if it has no cycle of odd length.

One direction is easy: a cycle alternates sides, so it returns to its start side only after an even number of steps. For the other, color a vertex LL, its neighbours RR, their neighbours LL, and so on (BFS); an odd cycle is the only way to reach a vertex from both sides. The BFS gives an algorithm that either 2-colors the graph or finds a conflict.

python · try it yourself
from collections import deque

def two_color(n, edges):
    adj = {v: [] for v in range(n)}
    for u, v in edges:
        adj[u].append(v); adj[v].append(u)
    side = {}
    for s in range(n):
        if s in side:
            continue
        side[s] = 0
        q = deque([s])
        while q:
            u = q.popleft()
            for w in adj[u]:
                if w not in side:
                    side[w] = 1 - side[u]; q.append(w)
                elif side[w] == side[u]:
                    return None, (u, w)
    return side, None

print(two_color(6, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)]))   # even cycle
print(two_color(5, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]))           # odd cycle
({0: 0, 1: 1, 5: 1, 2: 0, 4: 0, 3: 1}, None)
(None, (2, 3))

Matchings and Hall's theorem

A matching is a set of edges with no shared vertex. A matching covers LL if every vertex of LL is matched. For a set S⊆LS \subseteq L, let N(S)N(S) be the set of neighbours of SS in RR.

Hall's Theorem. There is a matching covering LL if and only if every subset S⊆LS \subseteq L satisfies ∣N(S)∣≥∣S∣\lvert N(S) \rvert \ge \lvert S \rvert.

The condition is clearly necessary: if 3 applicants are together qualified for only 2 jobs, they cannot all be placed. The surprise is that it is also sufficient (proof by strong induction on ∣L∣\lvert L \rvert, splitting on whether some proper subset is "tight" with ∣N(S)∣=∣S∣\lvert N(S) \rvert = \lvert S \rvert).

Corollary. If every vertex of LL has degree at least dd and every vertex of RR has degree at most dd, there is a matching covering LL. In particular, every regular bipartite graph has a perfect matching.

Finding a maximum matching

The augmenting path algorithm grows a matching: from an unmatched left vertex, search for a path that alternates unmatched/matched edges and ends at an unmatched right vertex; flipping the edges on that path adds one to the matching. When no augmenting path exists, the matching is maximum.

python · try it yourself
def max_matching(adj):
    """adj: dict left -> list of right vertices. Returns dict right -> left."""
    match = {}

    def try_assign(u, seen):
        for v in adj[u]:
            if v in seen:
                continue
            seen.add(v)
            if v not in match or try_assign(match[v], seen):
                match[v] = u
                return True
        return False

    for u in adj:
        try_assign(u, set())
    return match

skills = {
    "ana": ["backend", "data"],
    "ben": ["backend"],
    "chi": ["frontend", "backend"],
    "dev": ["data", "ops"],
    "eve": ["frontend"],
}
m = max_matching(skills)
print("matched:", sorted((u, v) for v, u in m.items()))
print("size:", len(m), "of", len(skills))
matched: [('ana', 'data'), ('ben', 'backend'), ('chi', 'frontend'), ('dev', 'ops')]
size: 4 of 5

Only 4 of 5 people can be placed. Hall's condition explains why: S={ben,chi,eve}S = \{\text{ben}, \text{chi}, \text{eve}\} has N(S)={backend,frontend}N(S) = \{\text{backend}, \text{frontend}\}, two jobs for three people.

Stable matching

When both sides have preferences, a matching of applicants to employers is stable if no applicant aa and employer ee prefer each other over their current partners (such a pair is a rogue couple). The Gale–Shapley algorithm always finds a stable matching: each unmatched applicant proposes to the best employer not yet tried; each employer keeps the best proposal so far and rejects the rest. It runs in O(n2)O(n^2) proposals, and the result is the best stable matching possible for every applicant (the proposing side). The U.S. National Resident Matching Program uses a variant.

In software

Matching algorithms assign tasks to workers, rides to drivers and ads to slots; with weights, the Hungarian algorithm finds a maximum-weight matching. Bipartite checks detect conflicts, such as whether a set of meetings can be split into two rooms when certain pairs cannot share a room.

Exercises

Exercise 1: Bipartite?

Which are bipartite: (a) C8C_8; (b) C7C_7; (c) a tree; (d) K3K_3?

Answer

(a) yes; (b) no; (c) yes; (d) no.

Solution

A graph is bipartite exactly when it has no odd cycle. C8C_8 is an even cycle; C7C_7 and K3K_3 (a triangle) are odd cycles; a tree has no cycles at all.

Exercise 2: Check Hall's condition

Left {1,2,3}\{1, 2, 3\}, right {a,b,c}\{a, b, c\}, edges 1a,1b,2a,3a1a, 1b, 2a, 3a. Is there a matching covering the left side?

Answer

No.

Solution

S={2,3}S = \{2, 3\} has N(S)={a}N(S) = \{a\}, so ∣N(S)∣=1<2\lvert N(S) \rvert = 1 < 2. Vertices 2 and 3 both need aa.

Exercise 3: Regular graphs

Every student in a class has exactly 3 favourite songs among 30, and every song is the favourite of exactly 3 students; there are 30 students. Can each student present a different favourite song?

Answer

Yes.

Solution

The student-song graph is 3-regular and bipartite. For SS a set of students there are 3∣S∣3\lvert S \rvert edges leaving SS, and they land on songs that each take at most 3 of them, so ∣N(S)∣≥∣S∣\lvert N(S) \rvert \ge \lvert S \rvert. Hall's theorem gives a perfect matching.

Exercise 4: Gale–Shapley (code)

Run proposals for applicants A, B, C with preferences A: x > y > z, B: y > x > z, C: x > y > z and employers x: B > A > C, y: A > B > C, z: A > B > C.

Answer

A–x, B–y, C–z.

Solution
python · try it yourself
apps = {"A": ["x", "y", "z"], "B": ["y", "x", "z"], "C": ["x", "y", "z"]}
emps = {"x": ["B", "A", "C"], "y": ["A", "B", "C"], "z": ["A", "B", "C"]}
rank = {e: {a: i for i, a in enumerate(p)} for e, p in emps.items()}
free, nxt, holds = list(apps), {a: 0 for a in apps}, {}
while free:
    a = free.pop(0)
    e = apps[a][nxt[a]]; nxt[a] += 1
    if e not in holds:
        holds[e] = a
    elif rank[e][a] < rank[e][holds[e]]:
        free.append(holds[e]); holds[e] = a
    else:
        free.append(a)
print(sorted((a, e) for e, a in holds.items()))
[('A', 'x'), ('B', 'y'), ('C', 'z')]

A proposes to x, B to y, C to x (rejected, x prefers A), C to y (rejected), C to z. No rogue pair: C would like x or y, but both prefer their current partner to C.

Test yourself

A graph is bipartite if and only if…

  1. it is connected
  2. it has no odd cycle
  3. it has an even number of vertices
  4. every vertex has even degree

Hall's condition for a matching covering LL is…

  1. ∣L∣=∣R∣\lvert L \rvert = \lvert R \rvert
  2. ∣N(S)∣≥∣S∣\lvert N(S) \rvert \ge \lvert S \rvert for every S⊆LS \subseteq L
  3. every vertex has degree 1
  4. the graph is a tree

What does an augmenting path do to a matching?

  1. Removes an edge
  2. Increases its size by one when its edges are flipped
  3. Checks Hall's condition
  4. Makes it stable