Bipartite Graph Checking
A graph is bipartite when its vertices split into two sides with every edge going across. To check, start anywhere, put the start on one side and its neighbours on the other, and keep alternating. Either every vertex gets a side with no clash, or two neighbours land on the same side, and then the graph has a cycle of odd length.
Two Sides, Every Edge Crossing
An undirected graph is bipartite if its vertices can be split into two groups, call them side A and side B, so that no edge joins two vertices of the same group. Workers and the jobs they can do, students and the courses they take, and the squares of a chessboard joined to their neighbours are all bipartite by construction.
Painting side A one colour and side B another gives a proper colouring with two colours, so a bipartite graph is the same thing as a 2-colorable graph. For three or more colours deciding is hard in general (see graph coloring); for two it takes one linear pass, because each choice forces the next.
The Odd Cycle Rule
Walk around any cycle in a bipartite graph. Each step crosses from one side to the other, so you are back on your starting side only after an even number of steps. A cycle with 3, 5 or any odd length cycle therefore cannot exist in a bipartite graph.
The reverse is also true (Kőnig, 1936): if a graph has no odd cycle, it is bipartite. The BFS check in the next section proves it constructively. It either finishes with two clean sides or stops at a clash, and every clash it can find comes with an odd cycle attached.
- Even cycles, trees and grids are bipartite
- Any triangle, and any graph containing one, is not
- A self-loop is a cycle of length 1, so it is never bipartite
Bipartite Check Using BFS
- Mark every vertex as having no side yet
- Pick a vertex with no side, put it on side A and in a queue
- Take a vertex u from the queue and look at each neighbour v
- If v has no side, give it the side opposite to u, record parent[v] = u, and queue it
- If v is on the same side as u, stop: the graph is not bipartite
- When the queue empties, go back to step 2 until every vertex has a side
The method spreads sides outward from a start vertex, one layer at a time. Layer 0 is side A, layer 1 side B, layer 2 side A again, and so on.
Terms, operations, and practical uses
Key terms
- Bipartite graphVertices split into two sides with every edge between the sides.
- Odd cycleA cycle with an odd number of edges; its presence is exactly what rules bipartite out.
- Clash edgeAn edge whose two ends have been given the same side.
- BFS layerThe vertices at one distance from the start; layers alternate sides.
Related lessons and problems
- Graph ColoringThree or more colours, where greedy is only a bound.
- Breadth-First SearchThe layer-by-layer search the check is built on.
- Network Flow and Maximum FlowMatching on a bipartite graph.
- Undirected Graph Cycle DetectionFinding any cycle, odd or even.
- Is Graph Bipartite? (problem)The standard interview version.
Code in Python, C++ and Java
from collections import deque
def two_colour(n, edges, starts=None):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
colour = [-1] * n
parent = [-1] * n
depth = [0] * n
for s in (range(n) if starts is None else starts):
if colour[s] != -1:
continue
colour[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for v in adj[u]:
if colour[v] == -1:
colour[v] = 1 - colour[u]
parent[v] = u
depth[v] = depth[u] + 1
queue.append(v)
elif colour[v] == colour[u]:
return None, odd_cycle(u, v, depth, parent)
return colour, None
def odd_cycle(u, v, depth, parent):
left, right = [u], [v]
while u != v:
if depth[u] >= depth[v]:
u = parent[u]
left.append(u)
else:
v = parent[v]
right.append(v)
return left + right[-2::-1]
def sides(colour):
return [i for i, c in enumerate(colour) if c == 0], [i for i, c in enumerate(colour) if c == 1]
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (2, 4), (4, 5), (6, 7)]
colour, _ = two_colour(8, edges)
print("bipartite, sides:", sides(colour))
_, cycle = two_colour(8, edges + [(1, 3)])
print("add edge 1-3, odd cycle:", cycle)
triangle = edges + [(7, 8), (8, 6)]
print("triangle in a second part, checked from 0 only, says bipartite:", two_colour(9, triangle, starts=[0])[1] is None)
print("same graph, every part checked, odd cycle:", two_colour(9, triangle)[1])
print("self-loop 0-0, odd cycle:", two_colour(1, [(0, 0)])[1])
print("no edges, sides:", sides(two_colour(3, [])[0]))#include <deque>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using Edge = pair<int, int>;
vector<int> oddCycle(int u, int v, const vector<int>& depth, const vector<int>& parent) {
vector<int> left = {u}, right = {v};
while (u != v) {
if (depth[u] >= depth[v]) {
u = parent[u];
left.push_back(u);
} else {
v = parent[v];
right.push_back(v);
}
}
for (int i = (int)right.size() - 2; i >= 0; i--) left.push_back(right[i]);
return left;
}
// Returns true and fills colour, or false and fills cycle.
bool twoColour(int n, const vector<Edge>& edges, const vector<int>& starts, vector<int>& colour, vector<int>& cycle) {
vector<vector<int>> adj(n);
for (auto [u, v] : edges) {
adj[u].push_back(v);
adj[v].push_back(u);
}
colour.assign(n, -1);
vector<int> parent(n, -1), depth(n, 0);
for (int s : starts) {
if (colour[s] != -1) continue;
colour[s] = 0;
deque<int> queue = {s};
while (!queue.empty()) {
int u = queue.front();
queue.pop_front();
for (int v : adj[u]) {
if (colour[v] == -1) {
colour[v] = 1 - colour[u];
parent[v] = u;
depth[v] = depth[u] + 1;
queue.push_back(v);
} else if (colour[v] == colour[u]) {
cycle = oddCycle(u, v, depth, parent);
return false;
}
}
}
}
return true;
}
vector<int> all(int n) {
vector<int> v(n);
for (int i = 0; i < n; i++) v[i] = i;
return v;
}
string show(const vector<int>& v) {
string s = "[";
for (size_t i = 0; i < v.size(); i++) s += (i ? ", " : "") + to_string(v[i]);
return s + "]";
}
string sides(const vector<int>& colour) {
vector<int> a, b;
for (int i = 0; i < (int)colour.size(); i++) (colour[i] == 0 ? a : b).push_back(i);
return "(" + show(a) + ", " + show(b) + ")";
}
int main() {
vector<Edge> edges = {{0, 1}, {1, 2}, {2, 3}, {3, 0}, {2, 4}, {4, 5}, {6, 7}};
vector<int> colour, cycle;
twoColour(8, edges, all(8), colour, cycle);
cout << "bipartite, sides: " << sides(colour) << "\n";
vector<Edge> extra = edges;
extra.push_back({1, 3});
twoColour(8, extra, all(8), colour, cycle);
cout << "add edge 1-3, odd cycle: " << show(cycle) << "\n";
vector<Edge> triangle = edges;
triangle.push_back({7, 8});
triangle.push_back({8, 6});
bool ok = twoColour(9, triangle, {0}, colour, cycle);
cout << "triangle in a second part, checked from 0 only, says bipartite: " << (ok ? "True" : "False") << "\n";
twoColour(9, triangle, all(9), colour, cycle);
cout << "same graph, every part checked, odd cycle: " << show(cycle) << "\n";
twoColour(1, {{0, 0}}, all(1), colour, cycle);
cout << "self-loop 0-0, odd cycle: " << show(cycle) << "\n";
twoColour(3, {}, all(3), colour, cycle);
cout << "no edges, sides: " << sides(colour) << "\n";
}import java.util.*;
public class Main {
static int[] colour;
static List<Integer> cycle;
static List<Integer> oddCycle(int u, int v, int[] depth, int[] parent) {
List<Integer> left = new ArrayList<>(List.of(u)), right = new ArrayList<>(List.of(v));
while (u != v) {
if (depth[u] >= depth[v]) {
u = parent[u];
left.add(u);
} else {
v = parent[v];
right.add(v);
}
}
for (int i = right.size() - 2; i >= 0; i--) left.add(right.get(i));
return left;
}
static boolean twoColour(int n, int[][] edges, int[] starts) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
adj.get(e[1]).add(e[0]);
}
colour = new int[n];
Arrays.fill(colour, -1);
int[] parent = new int[n], depth = new int[n];
for (int s : starts) {
if (colour[s] != -1) continue;
colour[s] = 0;
ArrayDeque<Integer> queue = new ArrayDeque<>(List.of(s));
while (!queue.isEmpty()) {
int u = queue.poll();
for (int v : adj.get(u)) {
if (colour[v] == -1) {
colour[v] = 1 - colour[u];
parent[v] = u;
depth[v] = depth[u] + 1;
queue.add(v);
} else if (colour[v] == colour[u]) {
cycle = oddCycle(u, v, depth, parent);
return false;
}
}
}
}
return true;
}
static int[] all(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = i;
return a;
}
static String sides() {
List<Integer> a = new ArrayList<>(), b = new ArrayList<>();
for (int i = 0; i < colour.length; i++) (colour[i] == 0 ? a : b).add(i);
return "(" + a + ", " + b + ")";
}
static int[][] plus(int[][] edges, int[]... more) {
int[][] out = Arrays.copyOf(edges, edges.length + more.length);
System.arraycopy(more, 0, out, edges.length, more.length);
return out;
}
public static void main(String[] args) {
int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {3, 0}, {2, 4}, {4, 5}, {6, 7}};
twoColour(8, edges, all(8));
System.out.println("bipartite, sides: " + sides());
twoColour(8, plus(edges, new int[]{1, 3}), all(8));
System.out.println("add edge 1-3, odd cycle: " + cycle);
int[][] triangle = plus(edges, new int[]{7, 8}, new int[]{8, 6});
boolean ok = twoColour(9, triangle, new int[]{0});
System.out.println("triangle in a second part, checked from 0 only, says bipartite: " + (ok ? "True" : "False"));
twoColour(9, triangle, all(9));
System.out.println("same graph, every part checked, odd cycle: " + cycle);
twoColour(1, new int[][]{{0, 0}}, all(1));
System.out.println("self-loop 0-0, odd cycle: " + cycle);
twoColour(3, new int[][]{}, all(3));
System.out.println("no edges, sides: " + sides());
}
}Step through it
Running on 0–1, 1–2, 2–3, 3–0, 2–4, 4–5, 6–7
Worked Example
Take 8 vertices and the edges 0–1, 1–2, 2–3, 3–0 (a square), 2–4, 4–5 (a tail) and 6–7 (a separate piece). BFS from 0 puts 0 on A, then 1 and 3 on B. From 1, vertex 2 goes to A; from 3, the edge back to 2 joins B to A, which is fine. From 2, vertex 4 goes to B, and from 4, vertex 5 goes to A.
The queue is empty but 6 and 7 have no side, so the search starts again at 6. The final split is A = {0, 2, 5, 6} and B = {1, 3, 4, 7}, and all 7 edges cross between them.
When It Fails: Printing the Odd Cycle
Add the edge 1–3. Both ends were put on side B by 0, so when the search looks along 1–3 it finds a clash and stops. A yes or no is often not enough; the odd cycle is the proof a user can check.
Walk up the parent links from 1 and from 3 until the two walks meet. Both stop at 0 after one step, so the cycle is 1 → 0 → 3 → 1, a triangle. In general a BFS edge joins two vertices in the same layer or in neighbouring layers, and neighbouring layers have opposite sides, so a clash edge always joins two vertices of one layer. Their paths up to the meeting vertex have the same length k. The cycle is k + k + 1 edges long, which is always odd.
- Keep parent[] and depth[] during the BFS; they cost O(V)
- Walk the deeper end up first, then both together until they meet
Every Piece Needs Its Own Start
A search from one vertex only sees that vertex's piece of the graph. Change the separate piece to a triangle 6–7–8 and start only from 0: the search finishes the square and the tail without a clash and answers 'bipartite', while the triangle is never looked at.
The outer loop over all vertices is what makes the answer about the whole graph. With it, the search restarts at 6, puts 7 and 8 on side B, and then finds the edge 7–8 joining two B vertices: the odd cycle 7 → 6 → 8 → 7.
DFS and Union-Find Versions
A depth-first search works the same way: give each unvisited neighbour the opposite side and recurse, and report a clash on any edge between two vertices of the same side. It is shorter to write but goes as deep as the longest path, so very large graphs need an explicit stack.
Union-find needs no traversal at all, which suits edges that arrive one at a time. For every vertex u, merge all of its neighbours into one set, because they must all share the side opposite u. If u itself ever ends up in the same set as one of its neighbours, the graph is not bipartite. The cost is nearly linear, O((V + E) α(V)).
Cost and Where It Is Used
Each vertex is queued once and each edge is looked at from both ends, so the BFS check takes O(V + E) time and O(V) extra memory for sides, parents and the queue. On an adjacency matrix it is O(V²).
Being bipartite is often the first step, not the goal. Maximum matching, such as assigning workers to jobs, runs on a bipartite graph (see network flow). Splitting people into two groups so that no two who dislike each other share a group, or scheduling two kinds of task that must alternate, are the same check with a different story.
- Is Graph Bipartite?: the check on an adjacency list
- Possible Bipartition: dislikes as edges, two groups as sides