A graph is bipartite if you can split its nodes into two groups with no edge inside a group. BFS colors nodes alternately; a same-color edge means it's impossible.
BFS from an uncolored node, painting it color A. Every neighbor gets the opposite color. Their neighbors flip back, and so on, like a checkerboard.
If you ever try to color a node the same as an already-colored neighbor, the two-group split is impossible.
bool isBipartite(vector<vector<int>>& graph) {
int n = graph.size();
vector<int> color(n, -1); // -1 = uncolored
for (int s = 0; s < n; s++) {
if (color[s] != -1) continue; // component already done
queue<int> q;
q.push(s); color[s] = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : graph[u]) {
if (color[v] == -1) {
color[v] = color[u] ^ 1; // opposite color
q.push(v);
} else if (color[v] == color[u]) {
return false; // same color → not bipartite
}
}
}
}
return true;
}
One BFS sweep; each vertex and edge visited once.
Color array plus the BFS queue.
A graph is 2-colorable exactly when it has no odd-length cycle.