Algo-Sim › Graph Traversal
Is Graph Bipartite?
Medium · Graph Traversal · step through it in Java, Python and C++ on your own input
Can the nodes be split into two groups so every edge crosses between them? BFS 2-colouring: a neighbour with the same colour means no.
Problem
An undirected graph is given as adjacency lists: graph[i] lists the neighbours of node i. Return true if the nodes can be split into two groups so that every edge joins nodes from different groups.
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ graph[i].length < n
- No self-loops or parallel edges; if v is in graph[u], u is in graph[v]
- The graph may be disconnected: check every component
Edge cases to test
- A disconnected graph: colour every component
- An odd cycle:
false - No edges:
true
Follow-up questions
- Why does an odd cycle fail?
- Colours must alternate along a cycle, which is only possible when its length is even.
- What is the union-find alternative?
- Union each node’s neighbours together and fail if a node ends in the same set as a neighbour.
Solution
Java
public boolean isBipartite(int[][] graph) {
int n = graph.length;
// color: 0 = none yet, 1 = red, -1 = blue
int[] color = new int[n];
for (int start = 0; start < n; start++) {
if (color[start] != 0) continue;
color[start] = 1;
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(start);
while (!queue.isEmpty()) {
int node = queue.poll();
for (int next : graph[node]) {
if (color[next] == 0) {
color[next] = -color[node];
queue.offer(next);
} else if (color[next] == color[node]) {
return false;
}
}
}
}
return true;
}Python
from collections import deque
def is_bipartite(graph):
n = len(graph)
# color: 0 = none yet, 1 = red, -1 = blue
color = [0] * n
for start in range(n):
if color[start] != 0:
continue
color[start] = 1
queue = deque([start])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if color[nxt] == 0:
color[nxt] = -color[node]
queue.append(nxt)
elif color[nxt] == color[node]:
return False
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isBipartite(vector<vector<int>> &graph) {
int n = int(graph.size());
// color: 0 = none yet, 1 = red, -1 = blue
vector<int> color = vector<int>(n);
for (int start = 0; start < n; start++) {
if (color[start] != 0)
continue;
color[start] = 1;
deque<int> queue = {};
queue.push_back(start);
while (!queue.empty()) {
int node = queue.front();
queue.pop_front();
for (int next : graph[node]) {
if (color[next] == 0) {
color[next] = -color[node];
queue.push_back(next);
} else if (color[next] == color[node]) {
return false;
}
}
}
}
return true;
}
};
More Graph Traversal problems
- Breadth-First Search (Easy)
- Depth-First Search (Easy)
- Course Schedule (cycle detection) (Medium)
- Graph Valid Tree (undirected cycle) (Medium)
- Number of Connected Components (DFS) (Medium)
- Clone Graph (Medium)
- Word Ladder (Hard)
- Open the Lock (Medium)