Sub topic 10
Modelling Real Problems as Bipartite Graphs
Earlier chapters covered testing a graph for bipartiteness and producing a proper two-colouring in O(V + E) time. This chapter is about the step before that: turning a real problem into a graph that is bipartite, or into a graph where "is it bipartite?" is the question you need answered. It assumes you know adjacency lists, BFS two-colouring, the odd cycle theorem, and how to read Python.
Two Ways a Problem Becomes Bipartite
Bipartite graphs show up in practice in two different ways, and confusing them causes most modelling mistakes.
- Bipartite by construction. The problem has two kinds of things, and every relation links one kind to the other. Examples are workers and jobs, students and courses, or users and products. You know the sides before you look at any edge, so testing is unnecessary. The bipartite structure is what you use to answer some other question, usually a matching question.
- Bipartiteness as the question. The problem has a single kind of thing and a "must be separated" relation between pairs. Examples are rival people, conflicting exams, or adjacent map regions that need different labels. The question is whether you can split the things into two groups so that every conflict crosses between the groups. That is exactly a two-colouring test.
The table lists common models of each kind.
| Problem | Vertices | Edges | Kind |
|---|---|---|---|
| Split people into two teams with no rivals on the same team | People | Rivalry | Question |
| Schedule exams into two time slots | Exams | Two exams share a student | Question |
| Assign workers to jobs | Workers and jobs | Worker can do job | Construction |
| Recommend products | Users and products | User bought product | Construction |
| Tile a board with dominoes | Board cells | Cells share a side | Construction (grid parity) |
| Course enrolment | Students and courses | Student takes course | Construction |
Conflict Splitting: When Bipartiteness Is the Question
Suppose you have to split five people into two teams so that no two rivals end up on the same team. Build one vertex per person and one undirected edge per rivalry. A valid split exists exactly when this conflict graph is bipartite, and the two colour classes are the teams.
Real input uses names, not integers, so the main modelling work is mapping names to indices and back.
from collections import deque
def two_colour(n, adj):
"""Return a list of colours (0 or 1) per vertex, or None if not bipartite."""
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 split_into_teams(people, rivalries):
"""Return (team_a, team_b) with no rivals together, or None if impossible."""
index = {name: i for i, name in enumerate(people)}
adj = [[] for _ in people]
for a, b in rivalries:
i, j = index[a], index[b]
adj[i].append(j) # rivalry is symmetric: add both directions
adj[j].append(i)
colour = two_colour(len(people), adj)
if colour is None:
return None
team_a = [p for p, c in zip(people, colour) if c == 0]
team_b = [p for p, c in zip(people, colour) if c == 1]
return team_a, team_b
people = ["Ana", "Ben", "Cai", "Dee", "Eli"]
rivalries = [("Ana", "Ben"), ("Ben", "Cai"), ("Cai", "Dee"), ("Eli", "Ana")]
print(split_into_teams(people, rivalries))
# (['Ana', 'Cai'], ['Ben', 'Dee', 'Eli'])
rivalries.append(("Dee", "Eli"))
print(split_into_teams(people, rivalries))
# None: Ana-Ben-Cai-Dee-Eli-Ana is a 5-cycleAdding the single rivalry between Dee and Eli closes a cycle of length 5. By the odd cycle theorem, no split can exist, and no amount of searching will find one.
Exam scheduling has the same shape. Each exam is a vertex, and two exams get an edge if at least one student sits both. Two time slots are enough exactly when the conflict graph is bipartite. With three or more slots the problem becomes graph colouring in general, which the last chapter shows is hard.
Common errors in conflict models
- Adding only one direction of the edge. If the input says "Ana dislikes Ben" and you store only
adj[Ana], BFS from Ben's side can miss the conflict. Conflict relations must be symmetrised. - Putting compatibility edges in a conflict graph. Edges must mean "must be in different groups." If your data says "these two should be together," merge them into one vertex first, or use the parity union-find from the next chapter, which can record both "same" and "different" constraints.
- Expecting a unique answer. Each connected component can have its colours swapped independently, so a graph with c components has 2^c valid splits. If the problem has extra constraints, such as Ana having to be on team A, handle them by choosing the starting colour of each component, not by rerunning the search.
Bipartite by Construction: Two Kinds of Entity
When the graph comes from a relation between two different sets, such as workers and the jobs they can do, it is bipartite before you run any code. The practical issue is giving every vertex a unique index. If worker 0 and job 0 share index 0, you have quietly merged two vertices and may even create odd cycles that do not exist in the real problem.
The standard fix is to offset the right side by the size of the left side.
def build_bipartite(left, right, relation):
"""Left vertices get 0..L-1, right vertices get L..L+R-1."""
L = len(left)
right_index = {name: L + k for k, name in enumerate(right)}
adj = [[] for _ in range(L + len(right))]
for i, name in enumerate(left):
for item in relation.get(name, []):
j = right_index[item]
adj[i].append(j)
adj[j].append(i)
return adj
workers = ["Ana", "Ben", "Cai"]
jobs = ["weld", "paint", "wire", "audit"]
can_do = {"Ana": ["weld", "wire"], "Ben": ["paint"], "Cai": ["wire", "audit", "paint"]}
adj = build_bipartite(workers, jobs, can_do)
side = [0] * len(workers) + [1] * len(jobs)
# Sanity check: every edge crosses sides.
assert all(side[u] != side[v] for u in range(len(adj)) for v in adj[u])
print(adj)
# [[3, 5], [4], [5, 6, 4], [0], [1, 2], [0, 2], [2]]The side array is the two-colouring, and you got it for free from the problem.
Projections destroy bipartiteness
A common next step is to "project" a two-sided graph onto one side. For example, you might link two users when they bought the same product. The projected graph is usually not bipartite: three users who bought the same product form a triangle. Projections are useful for similarity measures, but they discard the structure that matching and assignment algorithms depend on. They can also be large. A product bought by k users adds about k²/2 edges, while the original graph had only k edges for that product. Keep the original two-sided graph whenever the algorithm can work on it directly.
Grids and Parity: Hidden Bipartite Structure
Some graphs are bipartite because of a parity argument, not because of two named entity types. On a grid where cells connect to their up, down, left and right neighbours, every move changes r + c by exactly 1. Colouring each cell by (r + c) mod 2 is therefore a proper two-colouring. It is the chessboard pattern.
This gives quick impossibility proofs. Every domino placed on the board covers two adjacent cells, so it covers one cell of each colour. A full tiling needs equal numbers of the two colours. Remove two opposite corners of an 8×8 board and count:
rows, cols = 8, 8
blocked = {(0, 0), (7, 7)}
free = [(r, c) for r in range(rows) for c in range(cols) if (r, c) not in blocked]
even = sum((r + c) % 2 == 0 for r, c in free)
odd = len(free) - even
print(even, odd) # 30 32Both removed corners have even r + c, so 30 even cells remain against 32 odd ones, and no tiling exists. Equal counts do not guarantee a tiling, though. Deciding whether a tiling exists is a perfect-matching question on the grid's bipartite graph, which the next chapters introduce.
The parity argument depends on which moves you allow:
| Allowed moves | Bipartite? | Reason |
|---|---|---|
| Up, down, left, right | Yes | Each move changes r + c by 1 |
| Knight moves | Yes | Each move changes r + c by 1 or 3, always odd |
| King moves (including diagonals) | No | Three mutually adjacent cells form a triangle |
| Hexagonal neighbours | No | Hex grids contain triangles of cells |
The same reasoning applies to other domains. If every "step" in a problem flips some parity, such as a sign, the length of a sequence, or the number of swaps in a permutation, the state graph is bipartite with parity as the colour.
Checklist for Building the Model
- Decide what a vertex is. Make sure two different real objects never share an index.
- Decide what an edge means. In a conflict model, an edge must mean "must differ."
- Make relations symmetric before you build the adjacency lists.
- If the sides come from the problem, keep them, and assert that every edge crosses them.
- If bipartiteness is the question, run two-colouring. On failure, report the odd cycle so the user sees which constraints clash.
- Do not project a two-sided graph unless the algorithm really needs a one-sided graph.
Exercise
A club must split eight members into two committees, and some pairs refuse to serve together. After building the conflict graph, two_colour returns None. What should your program report to the user, and why is that more helpful than "impossible"?
Show answer
Report an odd cycle from the conflict graph, for example A-B-C-A or a 5-cycle, using the odd-cycle extraction technique. The cycle names the specific refusals that cannot all be satisfied together, so the user knows which constraint to drop. Any odd cycle is a complete proof of impossibility, since its members cannot alternate between two committees.
Exercise
You model students and courses with student indices 0..S-1 and course indices 0..C-1 stored in the same adjacency list without an offset. What can go wrong, even though the real relation is bipartite?
Show answer
Student i and course i become the same vertex. Edges from that merged vertex then mix student and course roles, which can create odd cycles and false conflicts. A bipartiteness check may fail, or a matching may pair a student with themselves. Offset course indices by S so all S + C vertices are distinct.
Exercise
On a 5×5 grid with up/down/left/right adjacency, can the board be tiled by dominoes after removing one cell? Which cells could be removed without the colour count ruling out a tiling?
Show answer
The board has 13 cells with even r + c and 12 with odd r + c. A tiling needs equal counts, so the removed cell must be one of the 13 even cells, such as a corner or the centre. Removing an odd cell leaves 13 against 11, which rules out a tiling. Equal counts are necessary but not always sufficient, so each even-cell case still needs a matching check or an explicit tiling.