Sub topic 8
A DFS Alternative
This chapter assumes you already know the BFS two-colouring algorithm from the earlier chapter, including its outer loop over every vertex for disconnected graphs. It also assumes you can read iterative and recursive Python and know how a stack differs from a queue. The question here is simple. What changes if you replace BFS with depth-first search (DFS)? Very little changes in the result, and the reasons for that tell you something useful about bipartite graphs. A few implementation details do matter, and Python makes one of them easy to get wrong.
Swapping the Queue for a Stack
The BFS algorithm keeps a queue of coloured vertices whose neighbours it has not yet examined. Nothing in the correctness argument depends on the queue's first-in, first-out order. Each time the algorithm processes a vertex u, it applies two rules to every neighbour v:
- If
vis uncoloured, give it the colour opposite touand schedule it for processing. - If
valready has the same colour asu, the graph is not bipartite.
These rules hold no matter what order the vertices come out in. A stack, which is last-in, first-out, therefore works just as well, and it turns the traversal into a depth-first one.
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]]
two_parts = [[1], [0], [3], [2]] # two separate edges
print(two_colour_dfs(4, square)) # [0, 1, 0, 1]
print(two_colour_dfs(3, triangle)) # None
print(two_colour_dfs(4, two_parts)) # [0, 1, 0, 1]The only change from the BFS version is deque.popleft() becoming list.pop(). The outer for start in range(n) loop is still there. It restarts the search in every component that has not been coloured yet, exactly as before.
Tracing the Stack
Take a graph with six vertices and the edges 0–1, 0–3, 1–2, 2–3, 3–4 and 4–5. It contains the 4-cycle 0–1–2–3 with a tail 3–4–5 hanging off it.
adj = [[1, 3], [0, 2], [1, 3], [0, 2, 4], [3, 5], [4]]| Step | Popped | Actions on neighbours | Stack after |
|---|---|---|---|
| 0 | none | colour 0 ← 0, push 0 | [0] |
| 1 | 0 | colour 1 ← 1, push; colour 3 ← 1, push | [1, 3] |
| 2 | 3 | 0 differs, ok; colour 2 ← 0, push; colour 4 ← 0, push | [1, 2, 4] |
| 3 | 4 | 3 differs, ok; colour 5 ← 1, push | [1, 2, 5] |
| 4 | 5 | 4 differs, ok | [1, 2] |
| 5 | 2 | 1 differs, ok; 3 differs, ok | [1] |
| 6 | 1 | 0 differs, ok; 2 differs, ok | [] |
The result is [0, 1, 0, 1, 0, 1]. The search reached vertex 5, at the end of the tail, before it came back to vertex 1, which is a neighbour of the start. BFS would have handled 1 and 3 first. The visiting order is very different, but the colours are exactly the same.
Why BFS and DFS Produce the Same Colouring
The colours match for a structural reason. In a connected bipartite graph, fix the colour of one vertex s. Every other vertex v must then get the colour colour(s) XOR (parity of the length of any path from s to v). All paths from s to v have the same parity. If one path were even and another odd, joining them would give a closed walk of odd length, and every closed walk of odd length contains an odd cycle. The odd cycle theorem rules that out.
So a connected bipartite graph has exactly two proper two-colourings, and each is the other with the colours swapped. Any traversal that starts at the same vertex with colour 0 must find the same one. BFS and DFS each build a spanning tree of the component, and they colour by the parity of depth in that tree. The trees differ, but tree-path parity always equals the parity of every other path, so the colours agree.
The two methods can disagree in two cases:
- Non-bipartite graphs. Both return
None, but they may find the conflict at different edges and at different points in the run. If you only need yes or no, this makes no difference. It does matter if you report which edge caused the failure. - Different start vertices or outer-loop order. A component's colouring can come out flipped. This is still a valid answer. Tests that compare against one fixed colouring will fail anyway, so check validity instead: every edge must join two different colours.
The Recursive Version and Python's Recursion Limit
DFS is usually written recursively, and the recursive two-colouring reads naturally:
def two_colour_recursive(n, adj):
"""Recursive DFS two-colouring. Fails on deep graphs in CPython."""
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
def path(n):
"""Adjacency list of the path 0 - 1 - ... - (n-1)."""
return [[j for j in (i - 1, i + 1) if 0 <= j < n] for i in range(n)]
print(two_colour_recursive(6, path(6))) # [0, 1, 0, 1, 0, 1]
try:
two_colour_recursive(5000, path(5000))
except RecursionError:
print("RecursionError on a 5000-vertex path")CPython's default recursion limit is about 1000 frames. A path, or any graph with a long simple path that DFS happens to follow, goes deeper than that and raises RecursionError. Calling sys.setrecursionlimit to raise the limit only moves the problem: if you set it high enough, the interpreter's C stack can overflow and crash the process with no Python traceback. Graphs from real data, such as road networks, dependency chains and grid puzzles, often contain paths thousands of vertices long.
The iterative version keeps its stack in an ordinary list on the heap, so it has no depth limit:
print(two_colour_dfs(100_000, path(100_000))[:6]) # [0, 1, 0, 1, 0, 1]Colour on Push, Not on Pop
The iterative code colours a vertex at the moment it pushes it. That choice is deliberate. Suppose you instead colour vertices only when you pop them, as some textbook DFS code does when it marks vertices visited on pop:
- A vertex can sit on the stack several times, once for each coloured neighbour that pushed it before it was popped. The stack can then grow to O(E) entries instead of O(V).
- You must skip popped vertices that are already coloured, and you need a separate record of which colour each push intended. Two pushes of the same vertex might carry conflicting colours, and that conflict is exactly the odd cycle you are looking for. It is easy to miss this.
Colouring on push means each vertex enters the stack at most once, and every conflict shows up as an ordinary same-colour check on an edge. The total work stays O(V + E): each vertex is popped once and each adjacency list is scanned once. The extra space is O(V) for the colour array and the stack.
It Is Not Quite a True DFS
The stack-based loop above does not visit vertices in true depth-first preorder. It pushes all of u's uncoloured neighbours at once and then goes deep into the last one. Recursive DFS goes into the first neighbour before it looks at the others. For colouring this makes no difference, because the argument above holds for any spanning tree.
The difference matters when an algorithm depends on properties of the DFS tree itself. One such property is that in an undirected graph every non-tree edge connects a vertex to one of its ancestors. To get a true DFS iteratively, push an iterator over each vertex's adjacency list and advance it one neighbour at a time. Keep this in mind for later chapters. For a plain yes/no bipartiteness test, the simple version is correct and faster.
Choosing Between BFS and DFS
| Criterion | BFS (queue) | Iterative DFS (stack) | Recursive DFS |
|---|---|---|---|
| Correctness | Yes | Yes | Yes, until the depth limit |
| Time | O(V + E) | O(V + E) | O(V + E) |
| Extra space | O(V) queue | O(V) stack | O(depth) call frames |
| Safe on long paths in Python | Yes | Yes | No |
| Conflict edge joins vertices of equal depth | Yes, which makes odd-cycle extraction simple | No | No |
| Fits existing DFS code | No | Partly | Yes |
Choose BFS when you will later want a short odd cycle as evidence that the graph is not bipartite. In BFS, the two endpoints of a conflicting edge have equal depth, and the next chapter relies on that fact. Choose iterative DFS when you already have a DFS pass, for example one that also counts components or finds bridges, and want to add colouring to it. Use recursive DFS only when the graph's depth is known to be small.
Exercise
Run twocolourdfs on the 5-cycle with adjacency list [[1, 4], [0, 2], [1, 3], [2, 4], [3, 0]]. Which vertex is being processed when the conflict is found, and which neighbour causes it?
Show answer
Vertex 0 gets colour 0, and popping it colours 1 and 4 with colour 1, so the stack is [1, 4]. Popping 4 colours 3 with colour 0 (0 is fine), so the stack is [1, 3]. Popping 3 colours 2 with colour 1 (4 is fine), so the stack is [1, 2]. Popping 2 finds neighbour 1, which is uncoloured-free and has colour 1, the same as 2. The function returns None while processing vertex 2, and the conflicting edge is 2–1.
Exercise
A colleague's tests for twocolourbfs assert exact outputs such as [0, 1, 0, 1, 0, 1]. Will those tests still pass if the implementation becomes twocolourdfs? Explain when they could fail.
Show answer
On bipartite inputs, yes, as long as the outer loop still starts each component at its lowest-numbered uncoloured vertex with colour 0. Each connected bipartite component has only two valid colourings, and fixing the start vertex's colour selects one of them, whatever the traversal order. The tests can fail if the start order or start colour changes, which flips a component, or if they check details of a non-bipartite run, such as which edge caused the conflict. Checking that every edge joins two different colours is the safer test.
Exercise
Why does colouring on push keep the stack at O(V), while marking on pop can need O(E)?
Show answer
With colouring on push, a vertex is coloured before it enters the stack and is never pushed again, so the stack holds at most V entries. With marking on pop, every already-processed neighbour can push a vertex before that vertex is popped, so a vertex of degree d can appear up to d times. Summed over all vertices, that gives O(E) entries.