Sub topic 11
Testing Whether a Graph Is Bipartite
A graph is bipartite if you can split its vertices into two groups so that every edge joins a vertex in one group to a vertex in the other. No edge stays inside a group. Many practical problems ask this question in other words. Can students be split into two teams so that no two rivals share a team? Can jobs be scheduled on two machines so that conflicting jobs never share a machine? Can a matching problem be modelled as "workers on the left, tasks on the right"?
This chapter assumes you already know:
- BFS with a FIFO queue and a visited structure, covered in earlier chapters
- BFS layers: each vertex's layer number is its edge distance from the source
- Running BFS from every unvisited vertex to cover all connected components
- Undirected graphs stored as adjacency lists, with every edge listed in both directions
Two-coloring as the working model
Picture the two groups as two colors, 0 and 1. A graph is bipartite exactly when you can color every vertex so that no edge joins two vertices of the same color. This is called a valid 2-coloring.
BFS gives you a coloring for free. Color the source 0. Its neighbors are in layer 1, so color them 1. Their undiscovered neighbors are in layer 2, so color them 0. In general, a vertex's color is its layer number mod 2. All that remains is to check every edge and confirm that its endpoints have different colors.
Why layer parity is the right coloring
In an undirected graph, an edge can never skip a layer. Suppose an edge joins u in layer i to v in layer j, with j ≥ i + 2. When BFS processed u, it would have discovered v and put it in layer i + 1, which contradicts j ≥ i + 2. So every edge falls into one of two cases:
| Edge type | Layers of endpoints | Colors under parity coloring |
|---|---|---|
| Between adjacent layers | `i` and `i + 1` | Different. The edge is fine. |
| Within one layer | `i` and `i` | Same. This is a conflict. |
If no edge lies inside a layer, the parity coloring is valid and the graph is bipartite. If some edge lies inside a layer, the graph is not bipartite, and the reason is not only that this particular coloring failed. A same-layer edge proves that no valid coloring exists.
A same-layer edge forces an odd cycle
Take a conflicting edge (u, v) with both endpoints in layer k. Follow parent pointers up the BFS tree from u and from v until the two paths meet at their lowest common ancestor w, which sits in some layer m < k. Each path from w down to u or v has k − m edges. Joining the two paths with the edge (u, v) makes a cycle of length 2(k − m) + 1, which is odd.
An odd cycle can never be 2-colored. Colors must alternate as you walk around the cycle, and after an odd number of steps you return to the starting vertex with the opposite color. So the standard theorem follows: a graph is bipartite if and only if it contains no odd cycle. BFS either finds a valid coloring or exposes an odd cycle.
The algorithm
The color dictionary does two jobs. It works as the visited set, and it stores the answer. The outer loop starts a new BFS from every vertex that has no color yet, so every connected component gets checked.
from collections import deque
def is_bipartite(graph):
color = {}
for source in graph:
if source in color:
continue
color[source] = 0
queue = deque([source])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in color:
color[neighbor] = 1 - color[node]
queue.append(neighbor)
elif color[neighbor] == color[node]:
return False
return True
square = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}
triangle = {0: [1, 2], 1: [0, 2], 2: [0, 1]}
print(is_bipartite(square)) # True
print(is_bipartite(triangle)) # FalseThe elif branch runs for every edge whose far endpoint already has a color. Edges that lead to a parent or to the next layer pass the check. Only a same-layer edge fails it. The code never compares layer numbers directly. Parity is enough, because edges span at most one layer, so a same-colored neighbor must be in the same layer.
Returning the two sides
You often need the partition itself, not just a yes or no answer. The function below returns the two groups, or None when the graph is not bipartite. The test graph has three components, including an isolated vertex.
from collections import deque
def two_color(graph):
color = {}
for source in graph:
if source in color:
continue
color[source] = 0
queue = deque([source])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in color:
color[neighbor] = 1 - color[node]
queue.append(neighbor)
elif color[neighbor] == color[node]:
return None
left = [v for v in graph if color[v] == 0]
right = [v for v in graph if color[v] == 1]
return left, right
graph = {
'a': ['x', 'y'],
'b': ['x'],
'x': ['a', 'b'],
'y': ['a'],
'p': ['q'],
'q': ['p'],
'z': [],
}
print(two_color(graph)) # (['a', 'b', 'p', 'z'], ['x', 'y', 'q'])Each component is colored on its own, so a bipartite graph with c components has 2^(c−1) valid partitions. You can swap the colors inside any component except the first, and the coloring stays valid. BFS returns one of them. Do not assume it matches a partition someone else computed.
Complexity
The check adds O(1) work to each edge examination, so the running time is the same as plain BFS: O(V + E). The outer loop touches every vertex once. Each adjacency list is scanned once, after its vertex is dequeued. The color dictionary and the queue use O(V) extra space. The function can return early at the first conflict, but in the worst case, a bipartite graph, it examines every edge.
Common errors and edge cases
Checking only one component
If you run a single BFS from one vertex and return True, the program ignores every other component. A graph made of a square and a separate triangle is not bipartite, but a one-source check that starts in the square reports that it is. The outer for source in graph loop exists to prevent this.
One-way adjacency lists
Bipartiteness is defined for undirected graphs. The algorithm relies on each edge appearing in both endpoints' lists. If each edge is stored only once, the results stop meaning anything:
from collections import deque
def is_bipartite(graph):
color = {}
for source in graph:
if source in color:
continue
color[source] = 0
queue = deque([source])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in color:
color[neighbor] = 1 - color[node]
queue.append(neighbor)
elif color[neighbor] == color[node]:
return False
return True
one_way = {'a': [], 'b': [], 'c': ['a', 'b']}
both_ways = {'a': ['c'], 'b': ['c'], 'c': ['a', 'b']}
print(is_bipartite(one_way)) # False (wrong: a-c-b is a path)
print(is_bipartite(both_ways)) # TrueIn one_way, vertices a and b each start their own BFS with color 0 and have no outgoing edges. When c starts a third BFS, also with color 0, it sees a already colored 0 and reports a conflict that does not exist.
Vertices missing from the dictionary
If a vertex appears only inside other vertices' lists and is not a key, graph[node] raises KeyError when BFS dequeues it. An isolated vertex that is not a key never gets a color, so it is left out of any partition you return. Make sure every vertex is a key, even if its list is empty.
Self-loops and parallel edges
A self-loop (v, v) is a cycle of length 1, which is odd, so a graph with a self-loop is never bipartite. The code handles this correctly: v sees itself as a neighbor with its own color and returns False. Parallel edges do no harm. They are checked twice and give the same result both times.
Recognizing bipartite structure without running code
Some graph families are always bipartite:
| Graph family | Bipartite? | Reason |
|---|---|---|
| Trees and forests | Yes | They contain no cycles at all |
| Even cycles | Yes | Colors alternate around the cycle |
| Odd cycles | No | They are odd cycles by definition |
| Grid graphs with 4-neighbor moves | Yes | Color each cell by `(row + col) % 2` |
| Complete graph on 3 or more vertices | No | It contains a triangle |
When a problem's graph clearly belongs to one of these families, you may not need the BFS check at all.
Exercises
Exercise
BFS from vertex 0 on an undirected graph puts vertices 5 and 8 in layer 3, and their lowest common ancestor in the BFS tree is in layer 1. There is an edge between 5 and 8. How long is the odd cycle this exposes?
Show answer
Each tree path from the ancestor down to 5 or to 8 has 3 − 1 = 2 edges. Adding the edge (5, 8) gives 2 + 2 + 1 = 5 edges, so the cycle has length 5.
Exercise
A graph has two components: a 4-cycle and a 7-cycle. A student runs a single BFS from a vertex of the 4-cycle and reports "bipartite". What went wrong, and what is the correct answer?
Show answer
A single BFS covers only the component that contains the source, so the 7-cycle was never examined. The 7-cycle is an odd cycle, so the graph is not bipartite. The fix is to start a BFS from every vertex that has no color yet.
Exercise
Why can the bipartiteness check compare only colors (layer parity), and not exact layer numbers, and still detect exactly the same-layer edges?
Show answer
In an undirected BFS, every edge joins vertices whose layers differ by 0 or 1. A difference of 1 always gives different parities. A difference of 0 always gives equal parities. So two endpoints have the same color exactly when they are in the same layer.
Exercise
You are given edges as a list of pairs, such as [(1, 2), (2, 3), (3, 1)], and build the graph with graph[u].append(v) only. Is is_bipartite guaranteed to return the right answer? Explain.
Show answer
No. The algorithm assumes every edge appears in both endpoints' adjacency lists. With one-way lists, separate BFS runs can give connected vertices arbitrary starting colors, which can produce false conflicts, and some edges are never examined from one side. Add both graph[u].append(v) and graph[v].append(u).