import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Graph {
private Set<Integer> marked = new HashSet<>();
private Map<Integer, Set<Integer>> neighbors = new HashMap<>();
private boolean isBipartite = true;
private Map<Integer, Boolean> isRed = new HashMap<>();
public Set<Integer> getPoints() {
return neighbors.keySet();
}
public int size() {
return getPoints().size();
}
public long edgeSize() {
return neighbors.values().stream()
.collect(Collectors.summingLong(Set::size)) / 2;
}
public void addEdge(int a, int b) {
neighbors.computeIfAbsent(a, k -> new HashSet<Integer>()).add(b);
neighbors.computeIfAbsent(b, k -> new HashSet<Integer>()).add(a);
}
public void colorGraph() {
for(Integer s : neighbors.keySet()) {
if(!marked.contains(s)) {
dfs(s, true);
}
}
}
private void dfs(Integer v, Boolean color) {
marked.add(v);
isRed.put(v, !color);
for(Integer w : neighbors.get(v)) {
if(!marked.contains(w)) {
dfs(w, isRed.get(v));
} else if (isRed.get(v) == isRed.get(w)){
this.isBipartite = false;
}
}
}
public static void main(String... args) {
Graph g = new Graph();
// change the number of points and edges here.
for (int i = 0; i < 7; i++) {
g.addEdge(i, i + 1);
g.addEdge(i, i + 2);
}
for (int i = 15; i < 17; i++) {
g.addEdge(i, i + 1);
}
g.addEdge(19, 19);
g.colorGraph();
System.out.println("strict graph {");
g.isRed.entrySet().forEach(i -> {
System.out.println(i.getKey() + "[color=" + (i.getValue() ? "red" : "blue") + "];");
});
g.neighbors
.keySet()
.stream()
.forEach(
i -> {
Stream.of(g.neighbors.get(i))
.flatMap(j -> j.stream())
.forEach(
k -> System.out.println(i + "--" + k + ";"));
});
System.out.println("}");
System.out.println("number of points: " + g.size());
System.out.println("number of edges: " + g.edgeSize());
System.out.println("the graph is bipartite: " + g.isBipartite);
}
}