-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (31 loc) · 942 Bytes
/
Solution.java
File metadata and controls
33 lines (31 loc) · 942 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
package isGraphBipartite;
public class Solution {
public boolean isBipartite(int[][] graph) {
int length = graph.length;
if (length == 0) {
return false;
}
int[] color = new int[length];
for (int i = 0; i < graph.length; i++) {
if (color[i] == 0) {
if (!isBipartite(graph, i, 1, color)) {
return false;
}
}
}
return true;
}
private boolean isBipartite(int[][] graph, int node, int currentColor, int[] color) {
if (color[node] == 0) {
color[node] = currentColor;
for (int nextNode : graph[node]) {
if (!isBipartite(graph, nextNode, -currentColor, color)) {
return false;
}
}
} else if (color[node] != currentColor) {
return false;
}
return true;
}
}