785. Is Graph Bipartite?
Problem
graph[u] lists the neighbours of node u in an undirected graph (no self-loops or duplicate edges; it may be disconnected). Decide whether its nodes can be split into two sets so that every edge joins nodes from different sets.
Example: [[1,3],[0,2],[1,3],[0,2]] → true; [[1,2,3],[0,2],[0,1,3],[0,2]] → false
Two-color each component with BFS; an edge between same colors → not bipartite (odd cycle).
Complexity: O(V + E).
class Solution:
def isBipartite(self, graph: List[List[int]]) -> bool:
color = [-1] * len(graph)
for s in range(len(graph)):
if color[s] != -1:
continue
color[s] = 0
q = deque([s])
while q:
u = q.popleft()
for v in graph[u]:
if color[v] == -1:
color[v] = 1 - color[u]
q.append(v)
elif color[v] == color[u]:
return False
return True
assert Solution().isBipartite([[1, 2, 3], [0, 2], [0, 1, 3], [0, 2]]) is False
assert Solution().isBipartite([[1, 3], [0, 2], [1, 3], [0, 2]]) is True
class Solution {
public boolean isBipartite(int[][] graph) {
int n = graph.length;
int[] color = new int[n];
Arrays.fill(color, -1);
for (int s = 0; s < n; s++) {
if (color[s] != -1) continue;
color[s] = 0;
Deque<Integer> q = new ArrayDeque<>(List.of(s));
while (!q.isEmpty()) {
int u = q.poll();
for (int v : graph[u]) {
if (color[v] == -1) { color[v] = 1 - color[u]; q.add(v); }
else if (color[v] == color[u]) return false;
}
}
}
return true;
}
}
func isBipartite(graph [][]int) bool {
color := make([]int, len(graph))
for i := range color {
color[i] = -1
}
for s := range graph { // the graph may be disconnected
if color[s] != -1 {
continue
}
color[s] = 0
q := []int{s}
for len(q) > 0 {
u := q[0]
q = q[1:]
for _, v := range graph[u] {
if color[v] == -1 {
color[v] = 1 - color[u]
q = append(q, v)
} else if color[v] == color[u] {
return false
}
}
}
}
return true
}