Sub topic 6
Handling Disconnected Graphs
The earlier chapters tested bipartiteness by running a breadth-first search (BFS) from one start vertex. That works only when every vertex can be reached from the start. Real inputs often contain several separate pieces: a social graph with isolated users, a scheduling graph where some exams share no students, or a map with islands. This chapter covers what changes when the graph is disconnected, why the fix is a small outer loop, and which mistakes cause wrong answers.
This chapter assumes you can read Python and already know the BFS two-colouring from the previous chapter. It also assumes you know what a connected component is: a maximal set of vertices in which every pair is joined by some path.
Why One Search Is Not Enough
A BFS from vertex s visits exactly the component that contains s. It never crosses into another component, because no edge leads there. If the algorithm stops after that one search, it has checked only part of the graph.
A disconnected graph is bipartite exactly when every component is bipartite. There is no edge between components, so no edge can join two vertices that sit in different components. That means no constraint links their colours either. Each component is a separate problem.
The code below shows the bug that results from forgetting this.
from collections import deque
def two_colour_from_zero(n, adj):
"""BUGGY: only explores the component that contains vertex 0."""
colour = [-1] * n
colour[0] = 0
queue = deque([0])
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
# Component A: the edge 0-1. Component B: the triangle 2-3-4.
adj = [[1], [0], [3, 4], [2, 4], [2, 3]]
print(two_colour_from_zero(5, adj)) # [0, 1, -1, -1, -1]The function returns a list instead of None, so a caller would conclude the graph is bipartite. The triangle in component B is an odd cycle, so that conclusion is false. The leftover -1 values are the only sign that anything went wrong, and code that only checks result is None will never look at them.
The Outer Loop
The fix is to try every vertex as a possible start. If a vertex is already coloured, an earlier search reached it and it belongs to a component that has been handled. If it is still uncoloured, it is the first vertex seen from a new component, so the algorithm colours it 0 and runs BFS from it.
The colour array does double duty here. A value of -1 means "not yet visited" and any other value means "visited, with this colour". You do not need a separate visited set. Do not reset colour between searches, because that array is what stops the loop from re-colouring components it has already finished.
Labelling Components and Reporting Each One
The version in the previous chapter returns None at the first conflict. That suits a yes-or-no question. Sometimes you need more detail, such as which components are fine and which are not. A conflict-splitting tool, for example, might process the good groups and flag the bad ones for a human to look at.
The function below finishes every component, records a component id for each vertex, and stores one flag per component.
from collections import deque
def bipartite_report(n, adj):
"""Colour every component.
Returns (colour, comp, ok):
colour[v] is 0 or 1,
comp[v] is the id of v's component,
ok[c] is True if component c is bipartite.
"""
colour = [-1] * n
comp = [-1] * n
ok = []
for start in range(n):
if colour[start] != -1:
continue
c = len(ok)
ok.append(True)
colour[start] = 0
comp[start] = c
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if colour[v] == -1:
colour[v] = 1 - colour[u]
comp[v] = c
queue.append(v)
elif colour[v] == colour[u]:
ok[c] = False # keep going so every vertex gets a label
return colour, comp, ok
# Edge 0-1, triangle 2-3-4, isolated vertex 5.
adj = [[1], [0], [3, 4], [2, 4], [2, 3], []]
colour, comp, ok = bipartite_report(6, adj)
print(comp) # [0, 0, 1, 1, 1, 2]
print(ok) # [True, False, True]
print(all(ok)) # FalseWhen a component has a conflict, the colours recorded for it are not a proper colouring. Use them only for components whose flag is True.
Do not return early inside the inner loop of this version. An early return would leave part of the current component unlabelled and skip every later component, so the report would be incomplete.
Components Are Coloured Independently
Each BFS gives its start vertex colour 0. That choice is arbitrary. Inside one connected bipartite component, the colour of the first vertex decides every other colour, because each edge forces its endpoints to differ and every vertex is linked to the start by a path. So a connected bipartite component has exactly two proper colourings, one the swap of the other.
Separate components do not constrain each other, so you can swap one component's colours without touching the rest.
def flip_component(colour, comp, c):
"""Swap colours 0 and 1 inside component c only."""
return [1 - col if comp[v] == c else col for v, col in enumerate(colour)]
def is_proper(adj, colour):
return all(colour[u] != colour[v] for u in range(len(adj)) for v in adj[u])
# Two separate edges: 0-1 and 2-3.
adj = [[1], [0], [3], [2]]
colour, comp, ok = bipartite_report(4, adj)
print(colour) # [0, 1, 0, 1]
flipped = flip_component(colour, comp, 1)
print(flipped) # [0, 1, 1, 0]
print(is_proper(adj, colour), is_proper(adj, flipped)) # True TrueThis independence leads to a counting rule. If a bipartite graph has c components, it has exactly 2**c proper two-colourings. An isolated vertex counts as a component and doubles the total, since it can take either colour.
Independence also matters in applications. Suppose you split students into two rooms so that no two rivals share a room, and you also want the rooms to be about the same size. The answer from BFS might be lopsided. Flipping whole components lets you rebalance without breaking any constraint. This becomes a subset-sum-style choice over the components, and it is outside what plain two-colouring does on its own.
Building the Adjacency List Correctly
Many disconnected-graph bugs come from building the input wrong. Traversal is rarely the cause. Two problems come up often.
Missing isolated vertices
If you build the graph from an edge list and learn the vertex set from the edges alone, vertices with no edges disappear. They never break bipartiteness, but they do get dropped from the output. A room assignment that leaves out a student with no rivals is still a wrong assignment. Pass the vertex count explicitly:
def build_adj(n, edges):
"""Undirected adjacency list for vertices 0..n-1, including isolated ones."""
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
return adj
print(build_adj(4, [(0, 1)])) # [[1], [0], [], []]One-way edges give false negatives
The colouring rule assumes every edge appears in both endpoints' lists. If an edge is stored only once, the outer loop can colour both of its endpoints separately as starts of "different components" and then report a conflict that is not real.
from collections import deque
def 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)
elif colour[v] == colour[u]:
return None
return colour
one_way = [[], [0]] # edge stored only as 1 -> 0
print(two_colour(2, one_way)) # None, which is wrong: a single edge is bipartite
both_ways = [[1], [0]]
print(two_colour(2, both_ways)) # [0, 1]Here is what happens. Vertex 0 has an empty list, so the first search colours it 0 and stops. Vertex 1 is still uncoloured, so it starts a second search with colour 0. It then sees neighbour 0, which also has colour 0, and the function reports a conflict. On a connected graph with a single start, the same mistake might go unnoticed. The outer loop exposes it, because it assumes that an uncoloured vertex shares no edges with anything already coloured.
Edge Cases at a Glance
| Input | Components | Bipartite? | Behaviour of the outer-loop algorithm |
|---|---|---|---|
| `n = 0` | 0 | Yes (vacuously) | Loop body never runs; returns `[]` |
| Isolated vertices only | `n` | Yes | Each vertex gets colour 0; `2**n` colourings exist |
| Self-loop `u-u` | any | No | `v == u` has the same colour as `u`; returns `None` |
| Parallel edges `u-v`, `u-v` | unchanged | Same as without duplicates | Second copy is checked and passes |
| Bad component not containing vertex 0 | 2 or more | No | Found only because of the outer loop |
| One-way adjacency | misleading | Possibly reported wrongly | Must symmetrise input first |
Cost of the Outer Loop
The outer loop adds one check per vertex. Each vertex is enqueued once over the whole run, not once per search, because the colour array persists between searches. Each adjacency list is scanned once. So the total work stays linear in the number of vertices plus edges, the same as for a connected graph. The next chapter works through this bound in detail.
Exercise
A graph has 7 vertices and edges 0-1, 1-2, 3-4, 5-6. It is bipartite. How many proper two-colourings does it have, and how many unordered bipartitions?
Show answer
The components are {0,1,2}, {3,4}, {5,6}, so c = 3. There are 23 = 8 proper two-colourings and 2(3-1) = 4 unordered bipartitions.
Exercise
A graph has 8 vertices and edges 0-1, 2-3, 4-5, 6-7. Vertex 7 has no other edges. How many proper two-colourings does it have? Now add an isolated vertex 8. What is the new count?
Show answer
There are four components, so there are 24 = 16 colourings. Adding isolated vertex 8 makes five components and 25 = 32 colourings. An isolated vertex doubles the count because it can take either colour.
Exercise
A colleague's bipartiteness test passes every unit test but reports "bipartite" on a production graph whose vertices 10, 11 and 12 form a triangle with no other edges. What is the most likely bug?
Show answer
The function runs BFS only from vertex 0, or from one chosen start, and never restarts at uncoloured vertices. The triangle sits in a separate component that is never visited. The fix is an outer loop over all vertices that starts a new BFS at each vertex still marked -1.
Exercise
Why does storing each edge in only one endpoint's adjacency list cause the outer-loop algorithm to report false conflicts, and why might a single-start BFS on a connected graph hide the same mistake?
Show answer
The outer loop assumes that an uncoloured vertex has no edges to already-coloured vertices, since otherwise BFS would have reached it. With one-way edges, a vertex can be unreachable along stored edges yet still point at a coloured vertex. It is then started with colour 0 and may clash with a neighbour that is also 0. A single BFS from a vertex that can reach everything along the stored directions may happen to give each vertex its colour before the vertex is ever checked against a neighbour, so the bug only appears for some start vertices or edge orders.