-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathIsBipartite.java
41 lines (34 loc) · 1.11 KB
/
IsBipartite.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
package algo.graph;
import ds.graph.Graph;
import java.util.HashMap;
import java.util.Map;
/**
* Created by sherxon on 4/1/17.
*/
public class IsBipartite extends BFS {
private Map<Integer, Boolean> color = new HashMap<>();
public IsBipartite(Graph graph) {
super(graph);
}
/**
* If there is a cycle with odd number of vertices, that graph cannot be bipartite. To check if graph has odd
* cycle, we traverse the graph with bfs and paint current node with white and its children with black.
* if any node has the same color as its parent, there is odd cycle.
*/
boolean hasOddCycle() {
for (Integer ver : graph.getVertices()) {
for (Integer nei : graph.getNeighbors(ver)) {
if (color.get(ver) == color.get(nei)) return true;
}
}
return false;
}
@Override
public void processVertex(Integer vertex) {
super.processVertex(vertex);
if (!color.containsKey(vertex))
color.put(vertex, true); // black
else
color.put(vertex, !color.get(queue.peek()));
}
}