-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path14. Is Graph Bipartite
80 lines (72 loc) · 2.27 KB
/
14. Is Graph Bipartite
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//Graph Coloring - DFS
class Solution {
public boolean isBipartite(int[][] g) {
int[] colors = new int[g.length];
for (int i = 0; i < g.length; i++)
if (colors[i] == 0 && !validColor(g, colors, 1, i))
return false;
return true;
}
boolean validColor(int[][] g, int[] colors, int color, int node) {
if (colors[node] != 0)
return colors[node] == color;
colors[node] = color;
for (int adjacent : g[node])
if (!validColor(g, colors, -color, adjacent))
return false;
return true;
}
}
//Graph Coloring - BFS
class Solution {
public boolean isBipartite(int[][] g) {
int[] colors = new int[g.length];
for (int i = 0; i < g.length; i++)
if (colors[i] == 0) {
Queue<Integer> q = new LinkedList<>();
q.add(i);
colors[i] = 1;
while (!q.isEmpty()) {
Integer node = q.poll();
for (int adjacent : g[node])
if (colors[adjacent] == colors[node])
return false;
else if (colors[adjacent] == 0) {
q.add(adjacent);
colors[adjacent] = -colors[node];
}
}
}
return true;
}
}
//Union Find
class Solution {
int[] parent;
public boolean isBipartite(int[][] graph) {
parent = new int[graph.length];
for(int i = 0; i < parent.length; i++) parent[i] = i;
for (int i=0; i<graph.length; i++) {
int[] adjs = graph[i];
for (int j=0; j<adjs.length; j++) {
if (find(i) ==find(adjs[j])) return false;
union(adjs[0], adjs[j]);
}
}
return true;
}
int find(int i) {
if (parent[i] == i) {
return parent[i];
}
parent[i] = find(parent[i]);
return parent[i];
}
void union(int i, int j) {
int parentI = find(i);
int parentJ = find(j);
if (parentI != parentJ) {
parent[parentI] = parentJ;
}
}
}