Sub topic 8
A DFS Alternative
This chapter assumes you have read the BFS two-colouring chapter and know how depth-first search (DFS) works. You should also be comfortable reading Python with lists used as stacks.
The BFS version colours a vertex's neighbours in waves, one layer at a time. Breadth is not what makes it correct. The algorithm only needs one rule: when a vertex is coloured, each uncoloured neighbour gets the opposite colour, and each coloured neighbour gets checked for a clash. Any traversal that applies this rule along every edge gives the same answer. DFS is the most common alternative.
Swapping the Queue for a Stack
Replace the deque with a plain list and popleft() with pop(). Nothing else changes.
def two_colour_dfs(n, adj):
"""Iterative DFS two-colouring; avoids Python's recursion limit."""
colour = [-1] * n
for start in range(n):
if colour[start] != -1:
continue
colour[start] = 0
stack = [start]
while stack:
u = stack.pop()
for v in adj[u]:
if colour[v] == -1:
colour[v] = 1 - colour[u]
stack.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]]
print(two_colour_dfs(4, square)) # [0, 1, 0, 1]
print(two_colour_dfs(3, triangle)) # NoneThe outer loop over start still restarts the search in every component that has not been visited yet, as in the BFS version. The running time stays O(V + E). Each vertex is pushed at most once, because it is pushed only at the moment it goes from uncoloured to coloured. Each adjacency list is scanned once, when its vertex is popped.
Why the Order Doesn't Matter
Within one component, the colour of a vertex is fixed once you choose the start vertex's colour. Every path from the start to a vertex x has the same parity in a bipartite component. Otherwise two paths of different parity would close an odd closed walk, and an odd closed walk always contains an odd cycle. So BFS, DFS, or any other order assigns each vertex the colour equal to the parity of its distance from the start. In a non-bipartite component, every order eventually checks an edge that the odd cycle forces into a clash, because every edge gets examined.
What does change is which clash you hit first and when. That matters only if you want to report a specific odd cycle, which a later chapter covers using BFS depths.
Common Errors
| Mistake | Consequence | Fix |
|---|---|---|
| Recursive DFS on a long path graph | `RecursionError` at around 1000 levels in CPython | Use an explicit stack, or raise the limit with care |
| Colouring a vertex at pop time instead of push time | The same vertex is pushed many times, so memory use is no longer bounded by V + E | Colour when pushing, as shown |
| Forgetting the outer `for start` loop | Components that cannot be reached from vertex 0 are never checked | Restart from every uncoloured vertex |
A recursive version is shorter and fine for small or shallow graphs:
def two_colour_rec(n, adj):
colour = [-1] * n
def visit(u):
for v in adj[u]:
if colour[v] == -1:
colour[v] = 1 - colour[u]
if not visit(v):
return False
elif colour[v] == colour[u]:
return False
return True
for s in range(n):
if colour[s] == -1:
colour[s] = 0
if not visit(s):
return None
return colour
print(two_colour_rec(4, [[1, 3], [0, 2], [1, 3], [2, 0]])) # [0, 1, 0, 1]A path of 100,000 vertices crashes two_colour_rec but two_colour_dfs handles it without trouble.
Exercise
Run twocolourdfs and the BFS two_colour on the same bipartite connected graph, starting from vertex 0. Can the two colour lists ever differ? What about a disconnected bipartite graph?
Show answer
On a connected bipartite graph they are identical. Each vertex's colour is the parity of its distance from vertex 0, and every path from vertex 0 to a given vertex has the same parity, whatever order the search takes. On a disconnected graph they also match, because both versions use the same outer loop and so pick the same start vertex in each component and give it colour 0.
Exercise
Why does colouring at pop time instead of push time break the O(V + E) memory bound?
Show answer
An uncoloured vertex could be pushed once by each neighbour popped before it, so the stack could hold up to E entries plus duplicates. Colouring at push time marks the vertex at once, so it is pushed at most once.