forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIsGraphBipairate.java
47 lines (39 loc) · 1.17 KB
/
IsGraphBipairate.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
// O(n2)
// O(n)
public boolean isBipartite(int[][] graph) {
int len = graph.length;
int[] color = new int[len];
Arrays.fill(color, -1);
for(int i=0;i<len;i++){
if(color[i] == -1){
color[i] = 1;
if(!dfs(i, graph, color)){
return false;
}
}
}
return true;
}
private boolean dfs(int index, int[][] graph, int[] color){
int currentColor = color[index];
for(int connectingIndex : graph[index]){
if(color[connectingIndex] == currentColor){
return false;
}
if(color[connectingIndex] == -1){
color[connectingIndex] = 1 - currentColor;
// if(currentColor == 1) {
// color[connectingIndex] = 0;
// }
// if(currentColor == 0) {
// color[connectingIndex] = 1;
// }
if(!dfs(connectingIndex, graph, color)){
return false;
}
}
}
return true;
}
}