Sub topic 11
Testing Whether a Graph Is Bipartite
This chapter assumes you know how BFS assigns layers (distances) to vertices and how running BFS from every unvisited vertex covers all connected components. The examples use undirected graphs stored as adjacency lists, where every edge appears in both endpoints' lists.
What Bipartite Means
A graph is bipartite if you can split its vertices into two groups so that every edge connects a vertex in one group to a vertex in the other. No edge stays inside a group. You can think of it as coloring each vertex with one of two colors so that every edge has two different colors at its ends.
Bipartite graphs show up when you model two kinds of things: students and courses, jobs and machines, or the pieces in a two-team scheduling problem. Some algorithms, such as bipartite matching, only work on graphs that pass this test.
A standard result gives the test: a graph is bipartite exactly when it has no cycle of odd length. A square (a 4-cycle) is bipartite. A triangle (a 3-cycle) is not.
Why BFS Layers Give the Coloring
BFS sorts vertices into layers by distance from the source. In an undirected graph, every edge joins two vertices in the same layer or in adjacent layers. An edge cannot skip a layer, because BFS would have discovered the far endpoint one step sooner.
So color each vertex by the parity of its layer: even layers get color 0 and odd layers get color 1. Edges between adjacent layers are then always fine. The only possible problem is an edge between two vertices in the same layer. Such an edge closes an odd cycle. Follow both endpoints up the BFS tree to their common ancestor. The two tree paths have equal length, and the extra edge adds one, so the cycle's total length is odd. So the graph is bipartite exactly when BFS finds no same-layer edge.
The Algorithm
The color dictionary also serves as the visited set. The outer loop starts a new BFS from every uncolored vertex, so the check covers every connected component.
from collections import deque
def is_bipartite(graph):
color = {}
for source in graph:
if source in color:
continue
color[source] = 0
queue = deque([source])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in color:
color[neighbor] = 1 - color[node]
queue.append(neighbor)
elif color[neighbor] == color[node]:
return False
return True
square = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}
triangle = {0: [1, 2], 1: [0, 2], 2: [0, 1]}
print(is_bipartite(square)) # True
print(is_bipartite(triangle)) # FalseThe check runs in O(V + E) time, the same as a plain BFS. Each vertex gets colored once, and each adjacency-list entry is examined once.
Common Errors
| Mistake | Effect | Fix |
|---|---|---|
| Running BFS only from one start vertex | Misses odd cycles in other components | Loop over all vertices and start BFS from each uncolored one |
| Storing edges in one direction only | Neighbors are missed and conflicts go unseen | Add every edge to both adjacency lists |
| Checking for conflicts only on newly discovered vertices | Same-layer edges between already colored vertices are never compared | Compare colors whenever the neighbor is already colored |
| Using a separate visited set out of sync with `color` | Vertices get visited but never colored, or the reverse | Let `color` be the visited set |
Exercises
Exercise
What does is_bipartite return for the 5-cycle {0: [1, 4], 1: [0, 2], 2: [1, 3], 3: [2, 4], 4: [3, 0]}, and which edge triggers the result?
Show answer
It returns False. BFS from 0 colors 1 and 4 with color 1, then colors 2 and 3 with color 0. Vertices 2 and 3 are both in layer 2, so when BFS processes 2 and checks neighbor 3, it sees two vertices with the same color. Edge 2–3 closes an odd cycle of length 5.
Exercise
The graph {0: [1], 1: [0], 2: [3, 4], 3: [2, 4], 4: [2, 3]} has two components. Why would a version that only runs BFS from vertex 0 give the wrong answer?
Show answer
BFS from 0 reaches only vertices 0 and 1, which form a bipartite component, so that version would return True. The triangle formed by 2, 3, and 4 is an odd cycle that BFS from 0 never reaches. The outer loop over all vertices starts a second BFS at vertex 2, finds the conflict, and returns False.