Is Graph Bipartite?
Pattern: Bipartite graphs
Try to colour every vertex with one of two colours so that every edge joins different colours. BFS from each uncoloured vertex: give it colour 1 and each neighbour the opposite colour. An edge between two vertices of the same colour means it is impossible.
Solve on LeetCodeSolve on GeeksforGeeks
The problem
graph[u] lists the neighbours of u (undirected). Return whether the vertices can be split into two groups with every
edge going between the groups. The graph may be in several pieces.
Think first
- If one vertex is in group A, where must its neighbours be?
- When does that rule fail?
- What about pieces not connected to the first vertex?
Hints
Brute force, and why it fails
Try every split of the vertices: O(2ⁿ × E).
The key insight
Each component has only two possible colourings, and BFS finds one or proves none exists.
Dry run
| colours | 1 -1 ? -1 |
|---|
graph [[1, 3], [0, 2], [1, 3], [0, 2]] (a square). Colour 0 with 1; 1 and 3 get -1.
The plan
for s uncoloured: colour[s] = 1; BFS: uncoloured neighbour gets -colour; same colour: false
Complexity
- Time
O(V + E)- Space
O(V)
Each vertex and edge once.
Edge cases
- No edges: true.
- A triangle: false.
- Several pieces, one of them bad: false.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean isBipartite(int[][] graph) {
int n = graph.length;
int[] color = new int[n]; // 0 uncoloured, 1 and -1 the two sides
for (int s = 0; s < n; s++) {
if (color[s] != 0) continue; // the graph may be in several pieces
color[s] = 1;
Queue<Integer> q = new ArrayDeque<>();
q.add(s);
while (!q.isEmpty()) {
int u = q.poll();
for (int v : graph[u]) {
if (color[v] == 0) { color[v] = -color[u]; q.add(v); } // neighbours go on the other side
else if (color[v] == color[u]) return false; // an edge inside one side
}
}
}
return true;
}
}C++
class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
int n = static_cast<int>(graph.size());
vector<int> color(n, 0); // 0 uncoloured, 1 and -1 the two sides
for (int s = 0; s < n; s++) {
if (color[s] != 0) continue; // the graph may be in several pieces
color[s] = 1;
queue<int> q;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : graph[u]) {
if (color[v] == 0) { color[v] = -color[u]; q.push(v); } // neighbours go on the other side
else if (color[v] == color[u]) return false; // an edge inside one side
}
}
}
return true;
}
};Python
from collections import deque
class Solution:
def isBipartite(self, graph: list[list[int]]) -> bool:
color = [0] * len(graph) # 0 uncoloured, 1 and -1 the two sides
for s in range(len(graph)):
if color[s]:
continue # the graph may be in several pieces
color[s] = 1
q = deque([s])
while q:
u = q.popleft()
for v in graph[u]:
if color[v] == 0:
color[v] = -color[u] # neighbours go on the other side
q.append(v)
elif color[v] == color[u]:
return False # an edge inside one side
return TrueCommon mistakes
- Colouring only from vertex 0.
- Treating the problem as needing a specific split.