Sub topic 5
Testing Bipartiteness with BFS
This chapter turns the odd cycle theorem into a working algorithm. It assumes you already know breadth-first search (BFS), adjacency lists, and the result from the previous chapter: a graph is bipartite exactly when it has no odd cycle. By the end, you will have a two-colouring function, a clear argument for why it is correct, and a list of the mistakes that most often break it.
The idea: colour by layer
BFS from a start vertex s visits the graph in layers. Layer 0 holds s. Layer 1 holds the neighbours of s. Layer d holds the vertices whose shortest path from s has d edges.
The two-colouring rule is simple: give each vertex the colour depth mod 2. Even layers get colour 0 and odd layers get colour 1. You never need to store the depth itself. A newly discovered vertex is one layer deeper than the vertex that discovered it, so its colour is the opposite of its parent's colour: 1 - colour[u].
Every edge of the graph now falls into one of two cases:
| Edge type | Depths of endpoints | Colours of endpoints | Effect on two-colouring |
|---|---|---|---|
| Between adjacent layers | `d` and `d + 1` | Different | Fine |
| Inside one layer | `d` and `d` | Same | Conflict: graph is not bipartite |
No third case exists. BFS can never produce an edge that skips a layer, such as an edge from depth 2 to depth 4. If u at depth 2 had a neighbour v, then v would be at depth at most 3, because u gives v a path of length 3. So every edge joins vertices whose depths differ by at most 1.
The algorithm
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 yet visited", so the code needs no separate visited set. A value of 0 or 1 is the vertex's side of the bipartition.
The inner loop handles three possibilities for each neighbour v of u:
vis uncoloured. Colour it opposite touand enqueue it.vis coloured differently fromu. The edge is consistent, so do nothing.vhas the same colour asu. The edge lies inside one layer, so stop and report failure.
The outer for start in range(n) loop restarts BFS from any vertex that is still uncoloured. This chapter traces a single connected graph. The next chapter explains why the restart is needed and what it means for disconnected graphs.
Why the algorithm is correct
You need two claims to trust the function: when it returns a colouring, that colouring is proper, and when it returns None, the graph really is not bipartite.
When it returns a colouring, every edge is checked
Every vertex is eventually dequeued, and when vertex u is dequeued the loop examines every edge (u, v) in adj[u]. Because the adjacency list stores each undirected edge in both directions, every edge is examined at least once, from whichever endpoint is dequeued first. At that moment the other endpoint is either uncoloured, in which case it receives the opposite colour, or already coloured, in which case the code compares the two colours. Colours never change after they are assigned. So if the function finishes without returning None, no edge joins two vertices of the same colour.
When it returns None, an odd cycle exists
Suppose the function stops on edge (u, v) with colour[u] == colour[v]. Both vertices were reached in the same BFS run, so they share a root s. The two vertices have the same depth parity, and their depths differ by at most 1, so their depths are equal. Call that depth d.
Follow the BFS parent pointers from u and from v back towards s. The two paths meet at a lowest common ancestor a at some depth d - k, where k ≥ 1. The path from a down to u has k edges, the path from a down to v also has k edges, and the edge (u, v) closes the loop. That cycle has 2k + 1 edges, which is odd. By the odd cycle theorem, the graph is not bipartite.
A later chapter turns this argument into code that returns the actual cycle as a certificate.
Conflicts are never missed
There is one more detail. Could a same-layer edge slip past the check? Suppose u and v are both at depth d and are adjacent. BFS dequeues every depth d - 1 vertex before any depth d vertex, and dequeuing the depth d - 1 vertices is what discovers all depth d vertices. So when the first of u and v is dequeued, the other one is already coloured, and the check colour[v] == colour[u] runs and fires. The function might stop on a different conflicting edge first, but it cannot finish while any conflict remains.
Worked trace
Take this six-vertex graph. Vertices 0, 1, 2, 3 form a square, and vertices 3, 4, 5 form a triangle.
adj = [
[1, 2], # 0
[0, 3], # 1
[0, 3], # 2
[1, 2, 4, 5], # 3
[3, 5], # 4
[4, 3], # 5
]
print(two_colour(6, adj)) # NoneThe trace below shows each dequeue step. The colour column lists vertices 0 to 5, with - for uncoloured.
| Step | Dequeued `u` | Neighbours examined | Action | Colours after | Queue after |
|---|---|---|---|---|---|
| 0 | (start) | colour 0 with 0 | `0 - - - - -` | `[0]` | |
| 1 | 0 | 1, 2 | colour both 1 | `0 1 1 - - -` | `[1, 2]` |
| 2 | 1 | 0, 3 | 0 differs, fine; colour 3 with 0 | `0 1 1 0 - -` | `[2, 3]` |
| 3 | 2 | 0, 3 | both differ from 1, fine | `0 1 1 0 - -` | `[3]` |
| 4 | 3 | 1, 2, 4, 5 | 1 and 2 fine; colour 4 and 5 with 1 | `0 1 1 0 1 1` | `[4, 5]` |
| 5 | 4 | 3, 5 | 3 fine; 5 has colour 1, same as 4 | stop | return `None` |
The square raised no conflict. The square is an even cycle, and its two paths from 0 to 3 have the same length, so vertex 3 receives a consistent colour from both sides. The triangle produced the conflict. Here the common ancestor of 4 and 5 is vertex 3, with k = 1, which gives the cycle 4, 3, 5 of length 2·1 + 1 = 3.
Common errors
Checking only uncoloured neighbours
A frequent bug is writing the loop as plain BFS with a visited set and never comparing colours of already-visited neighbours:
from collections import deque
def broken_two_colour(n, adj):
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)
return colour
triangle = [[1, 2], [0, 2], [0, 1]]
print(broken_two_colour(3, triangle)) # [0, 1, 1]: an invalid colouringThis version always returns a colouring, and the colouring is often wrong. Conflicts can only appear on edges to vertices that already have a colour, so the elif branch is the entire test.
One-directional adjacency lists
The correctness argument assumed that every undirected edge appears in both endpoints' lists. If you build adj from an edge list and append only adj[u].append(v), the algorithm can give wrong answers in either direction. Here is a false rejection:
adj = [[], [0]] # edge 0-1 stored only as 1 -> 0
print(two_colour(2, adj)) # None, although a single edge is bipartiteBFS from 0 sees no neighbours, so vertex 0 forms its own run with colour 0. BFS then restarts at 1, also with colour 0, and finds 0 already coloured the same. Always add both directions:
def build_adj(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return adj
print(two_colour(2, build_adj(2, [(0, 1)]))) # [0, 1]Colouring on dequeue instead of on enqueue
If you assign a colour only when a vertex leaves the queue, the same vertex can be enqueued several times before it is processed. The answers usually remain correct, but the queue can grow far beyond V entries and the running time is no longer linear. Colour a vertex at the moment you enqueue it, as the reference code does. That way the -1 test also acts as the visited test.
Testing against brute force
For small graphs, you can check every one of the 2^n colourings directly. Comparing the BFS result with that brute-force answer on random graphs catches most implementation bugs. Run this in the same file as two_colour and build_adj:
import itertools
import random
def brute_bipartite(n, edges):
for bits in itertools.product((0, 1), repeat=n):
if all(bits[u] != bits[v] for u, v in edges):
return True
return False
rng = random.Random(1)
for trial in range(2000):
n = rng.randint(1, 8)
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.3]
result = two_colour(n, build_adj(n, edges))
assert (result is not None) == brute_bipartite(n, edges)
if result is not None:
assert all(result[u] != result[v] for u, v in edges)
print("all trials agree")The second assertion matters. It confirms that a returned colouring is proper, and not merely that the yes-or-no answer matches.
Exercises
Exercise
Run two_colour by hand on the 5-cycle with adj = [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]. Which edge triggers the conflict, and what are the depths of its endpoints?
Show answer
Vertex 0 gets colour 0 at depth 0. Vertices 1 and 4 get colour 1 at depth 1. Dequeuing 1 colours 2 with 0 at depth 2. Dequeuing 4 colours 3 with 0 at depth 2. Dequeuing 2 examines neighbour 3, which also has colour 0, so the edge (2, 3) triggers the conflict. Both endpoints are at depth 2, and the cycle through their common ancestor 0 has 2·2 + 1 = 5 edges.
Exercise
Explain why, in a BFS tree, an edge can never join a vertex at depth 1 to a vertex at depth 3. Why does the two-colouring proof depend on this?
Show answer
If u at depth 1 is adjacent to v, then v has a path from the root of length at most 2, so its BFS depth is at most 2. Every edge therefore joins depths that differ by 0 or 1. The proof needs this because a same-colour edge then must have equal depths, and equal depths are what let the two parent paths have the same length k, giving an odd cycle of 2k + 1.
Exercise
A colleague's version marks a vertex as coloured only when it is dequeued. On a complete bipartite graph K(m, m), roughly how many times can a single vertex be enqueued, and why does that hurt?
Show answer
On the other side, all m vertices can each enqueue the same uncoloured vertex before it is dequeued, so a vertex can be enqueued up to about m times. The queue can then hold O(E) entries rather than O(V), and each extra entry rescans the vertex's whole adjacency list, which breaks the linear-time bound.