-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBipartiteGraph.java
More file actions
96 lines (81 loc) · 2.53 KB
/
BipartiteGraph.java
File metadata and controls
96 lines (81 loc) · 2.53 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Code by:@yinengy
* Time: 11/14/2018
*
* Correspond to the algorithm discussed at page 94-97
*/
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
public class BipartiteGraph extends AdjacencyList {
private boolean[] color; // represent two color by boolean
public BipartiteGraph(int numV) {
super(numV);
color = new boolean[numV + 1];
}
/**
* always label node 1 be first, and run BFS from 1 to label all other the nodes
* O(m+n)
*/
public void labelColor() {
Boolean[] Discovered = new Boolean[this.getNumV() + 1];
for (int n = 0; n < Discovered.length; n++) {
Discovered[n] = false;
}
Discovered[1] = true;
color[1] = true; // color start point to red
Queue<Integer>[] L = new Queue[this.getNumV() + 1];
L[0] = new LinkedBlockingQueue<>();
L[0].add(1);
int i = 0;
while (!L[i].isEmpty()) {
L[i + 1] = new LinkedBlockingQueue<>();
while (!L[i].isEmpty()) {
int u = L[i].remove();
LinkedList<Integer> edges = this.getEdges(u);
for (int v : edges) {
if (!Discovered[v]) {
Discovered[v] = true;
L[i + 1].add(v);
color[v] = ((i + 1) % 2 == 0); // odd layer be blue(false), even be red(true)
}
}
}
i++;
}
}
/**
* check all edges to find if two adjacent node are in the same color
* O(m + n)
*/
public boolean testBipartiteness() {
for (int v = 1; v <= this.getNumV(); v++) {
for (int u: this.getEdges(v)) {
if (color[u] == color[v]) {
return false;
}
}
}
return true;
}
/**
* return a 2-d array, each row represent one group with the same color.
* it should first must pass the bipartiteness test
*/
public LinkedList<Integer>[] getGroups() {
LinkedList<Integer>[] bipartite = new LinkedList[2];
bipartite[0] = new LinkedList<>();
bipartite[1] = new LinkedList<>();
for (int i = 1; i < color.length; i++) {
if (color[i]) {
bipartite[0].add(i);
} else {
bipartite[1].add(i);
}
}
return bipartite;
}
public boolean getColor(int v) {
return color[v];
}
}