Sub topic 2
Testing Bipartiteness with BFS
This chapter assumes you know adjacency lists, breadth-first search (BFS), and Big-O notation. It also assumes you accept the earlier result that a graph is bipartite exactly when it has no odd cycle.
The BFS Colouring Rule
BFS visits vertices in layers by distance from a start vertex. Give the start colour 0. Each time BFS discovers a new neighbour, give it the opposite colour of the vertex that found it. Then every layer has a single colour, and the colours alternate from one layer to the next.
Whenever BFS looks at an edge, one of three things is true:
| Neighbour state | Action |
|---|---|
| Uncoloured | Colour it `1 - colour[u]` and enqueue it |
| Opposite colour | Fine, continue |
| Same colour | Not bipartite, stop |
A same-colour edge joins two vertices at the same BFS depth. Those two vertices, together with their tree paths up to a common ancestor, form an odd cycle. That is why the test can stop as soon as it finds one.
Handling Disconnected Graphs
A single BFS reaches only one connected component. If you start BFS from vertex 0 only, an odd cycle in another component goes undetected and its vertices stay uncoloured. The fix is an outer loop that starts a new BFS from every vertex that is still uncoloured. Each component is coloured on its own. The graph is bipartite only if every component is.
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
square = [[1, 3], [0, 2], [1, 3], [2, 0]]
triangle = [[1, 2], [0, 2], [0, 1]]
two_edges = [[1], [0], [3], [2]] # two separate components
print(two_colour(4, square)) # [0, 1, 0, 1]
print(two_colour(3, triangle)) # None
print(two_colour(4, two_edges)) # [0, 1, 0, 1]Why Two-Colouring Runs in Linear Time
Each vertex gets a colour once and enters the queue once, which costs O(V) in total. Each vertex's adjacency list is scanned once, when that vertex leaves the queue. In an undirected graph every edge appears in two lists, so the scans cost O(2E) = O(E). The outer loop adds O(V) cheap checks. The total is O(V + E) time. The colour array and the queue use O(V) extra space.
Exercise
A graph has 6 vertices, with edges 0-1, 1-2, 3-4, 4-5 and 5-3. If you remove the outer loop and run BFS only from vertex 0, what does the function return, and what is the correct answer?
Show answer
Without the outer loop, BFS colours only vertices 0, 1 and 2 and returns [0, 1, 0, -1, -1, -1], which wrongly suggests the graph is bipartite. Vertices 3, 4 and 5 form a triangle, which is an odd cycle, so the correct answer is None.