-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIs Graph Bipartite.java
More file actions
33 lines (30 loc) · 936 Bytes
/
Is Graph Bipartite.java
File metadata and controls
33 lines (30 loc) · 936 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
enum Color { kWhite, kRed, kGreen }
class Solution {
public boolean isBipartite(int[][] graph) {
Color[] colors = new Color[graph.length];
Arrays.fill(colors, Color.kWhite);
for (int i = 0; i < graph.length; ++i) {
// Already colored, do nothing
if (colors[i] != Color.kWhite)
continue;
// colors[i] == Color.kWhite
colors[i] = Color.kRed; // Always paint w/ Color.kRed
// BFS
Queue<Integer> q = new ArrayDeque<>(Arrays.asList(i));
while (!q.isEmpty()) {
for (int sz = q.size(); sz > 0; --sz) {
final int u = q.poll();
for (final int v : graph[u]) {
if (colors[v] == colors[u])
return false;
if (colors[v] == Color.kWhite) {
colors[v] = colors[u] == Color.kRed ? Color.kGreen : Color.kRed;
q.offer(v);
}
}
}
}
}
return true;
}
}