Sub topic 6
Handling Disconnected Graphs
This chapter assumes you have read the BFS two-colouring chapter. You should be comfortable with adjacency lists, breadth-first search, and the rule that every edge must join vertices of different colours.
A single BFS only reaches vertices connected to its start vertex. Many real graphs are not connected. Examples include a conflict graph with unrelated groups of people, or a network with isolated machines. If you start one search and stop, part of the graph goes unchecked. This chapter shows why that matters and how to fix it.
What a single search misses
A connected component is a largest set of vertices in which every pair is joined by some path. Every graph splits into components. No edge runs between two of them.
The consequence for bipartiteness is direct:
- A graph is bipartite if and only if every one of its components is bipartite.
- Components never share an edge, so colouring one never constrains another.
The graph below has three components. One is a path, which is fine. One is a triangle, which is an odd cycle. One is an isolated vertex.
A BFS started at vertex 0 colours vertices 0, 1, 2 and finds no conflict. It never visits the triangle, so it wrongly reports that the graph is bipartite.
The fix: restart in every uncoloured vertex
Loop over all vertices. Whenever you reach one that is still uncoloured, it belongs to a component you have not explored yet. Start a fresh BFS there.
from collections import deque
def colour_component(start, adj, colour):
"""BFS-colour the component containing start. Return False on a conflict."""
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 False
return True
def two_colour(n, adj):
"""Colour every component; return the colours, or None if not bipartite."""
colour = [-1] * n
for s in range(n):
if colour[s] == -1 and not colour_component(s, adj, colour):
return None
return colour
# Path 0-1-2, triangle 3-4-5, isolated vertex 6.
adj = [[1], [0, 2], [1], [4, 5], [3, 5], [3, 4], []]
partial = [-1] * 7
print(colour_component(0, adj, partial)) # True (only component A checked)
print(partial) # [0, 1, 0, -1, -1, -1, -1]
print(two_colour(7, adj)) # None (triangle found)
# Remove edge 5-3 so component B becomes a path.
adj2 = [[1], [0, 2], [1], [4], [3, 5], [4], []]
print(two_colour(7, adj2)) # [0, 1, 0, 0, 1, 0, 0]The outer loop visits each vertex once. The inner BFS skips vertices that are already coloured, so each vertex is still dequeued only once in total. Restarting therefore adds no asymptotic cost. The next chapter covers the full cost analysis.
Each component colours independently
Each component gets its own start vertex, and that start vertex is arbitrarily given colour 0. Any colouring of a component stays valid when you swap its two colours, and the swap does not affect any other component. A bipartite graph with c components therefore has exactly 2^c proper two-colourings. An isolated vertex counts as a component and can take either colour.
This matters when a problem needs one particular colouring. Suppose you want to balance two teams, or a vertex must take a fixed colour. You can decide each component's orientation separately after the test passes.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Running BFS only from vertex 0 | Odd cycles in other components go undetected | Loop over all vertices and restart on uncoloured ones |
| Deriving `n` from the edge list | Isolated vertices are missing or cause index errors | Pass the vertex count explicitly and give every vertex an adjacency entry |
| Resetting `colour` for each component | Components are revisited, and runtime can become quadratic | Allocate `colour` once, outside the loop |
| Returning colours that still contain `-1` | Callers treat uncoloured vertices as valid | Return only after the outer loop finishes |
Exercise
A graph has 10 vertices. It has two bipartite components with edges and three isolated vertices. How many proper two-colourings does it have, and what would a BFS started only from vertex 0 report if one of the components were changed into a 5-cycle that did not contain vertex 0?
Show answer
There are 5 components, so there are 2^5 = 32 proper two-colourings. A single BFS from vertex 0 would never reach the 5-cycle, so it would wrongly report the graph as bipartite. The full loop would find the odd cycle and return None.
Exercise
In two_colour, why does the check colour[s] == -1 in the outer loop guarantee that each new BFS explores a component not seen before?
Show answer
BFS colours every vertex reachable from its start. So any vertex that is still uncoloured after earlier searches cannot be reachable from any earlier start vertex, which means it lies in a component that has not been explored yet.