Sub topic 5
Testing Bipartiteness with BFS
This chapter assumes you know how breadth-first search (BFS) works, can read Python, and remember the result from the previous chapter: a graph is bipartite exactly when it has no odd cycle. In this chapter, that theorem becomes an algorithm.
The idea: colour by layer
BFS explores a connected graph in layers. Layer 0 is the start vertex. Layer 1 holds its neighbours. Layer 2 holds their unvisited neighbours, and so on. Give every even layer colour 0 and every odd layer colour 1.
In an undirected graph, every BFS edge joins either two adjacent layers or two vertices in the same layer. An edge can never skip a layer. That leaves two cases:
- An edge between adjacent layers joins two different colours, which is fine.
- An edge inside one layer joins two vertices of the same colour. Each endpoint has a tree path back to a shared ancestor, and both paths have the same length. Those two paths plus the edge form a cycle of odd length, so the graph is not bipartite.
So the algorithm does not need to search for odd cycles directly. It colours as it goes and checks every edge it looks at.
The implementation
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
# A 4-cycle is bipartite; a triangle is not.
square = [[1, 3], [0, 2], [1, 3], [2, 0]]
triangle = [[1, 2], [0, 2], [0, 1]]
print(two_colour(4, square)) # [0, 1, 0, 1]
print(two_colour(3, triangle)) # NoneThe colour array does two jobs. A value of -1 means "not visited yet", so the code needs no separate visited set. Any other value records which side of the bipartition the vertex is on. The outer for start loop restarts BFS from each uncoloured vertex. The next chapter explains why that loop is needed.
Tracing the triangle
| Step | Dequeued | Neighbour | Action | colour |
|---|---|---|---|---|
| 0 | — | — | colour 0 as 0 | [0, -1, -1] |
| 1 | 0 | 1 | uncoloured, set to 1 | [0, 1, -1] |
| 2 | 0 | 2 | uncoloured, set to 1 | [0, 1, 1] |
| 3 | 1 | 0 | colours differ, fine | [0, 1, 1] |
| 4 | 1 | 2 | both are 1, conflict | return None |
Vertices 1 and 2 are both in layer 1, and the edge between them closes the cycle 0–1–2–0, which has length 3.
Common errors
- One-directional adjacency lists. The algorithm assumes every undirected edge appears in both endpoints' lists. If edge (u, v) is stored only under u, a conflict can still be caught from u's side, but the BFS from v will not reach u, so whole parts of the graph can go unexplored. Build the lists symmetrically.
- Checking only tree edges. The
elifbranch is the whole test. Code that skips already-coloured neighbours without comparing colours will report every graph as bipartite. - Self-loops. An edge (u, u) makes
colour[v] == colour[u]true, so the function returnsNone. That answer is correct, because a self-loop is a cycle of length 1. - Returning the colouring too early. Return the colouring only after every vertex has been processed. A partial result can hide a conflict that has not been checked yet.
Exercise
Run two_colour on the 5-cycle adj = [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]. Which edge triggers the conflict, and which BFS layer are its endpoints in?
Show answer
Vertex 0 gets colour 0. Vertices 1 and 4 get colour 1 (layer 1). Vertices 2 and 3 get colour 0 (layer 2). Dequeuing 1 and then 4 causes no conflict. When vertex 2 is dequeued, it checks neighbour 3, which also has colour 0, so the function returns None. The conflicting edge is (2, 3), and both endpoints are in layer 2.
Exercise
Why can a BFS edge in an undirected graph never join layer i to layer i + 2?
Show answer
When the layer-i vertex is dequeued, it colours and enqueues every uncoloured neighbour into layer i + 1. A neighbour that was still unvisited at that point therefore lands in layer i + 1, not later. So no neighbour can end up two layers away.