import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Digraph {
private Map<Integer, Set<Integer>> neighbors = new HashMap<>();
private Set<Integer> marked = new HashSet<>();
private boolean hasCircle = false;
private Map<Integer, Integer> path = new HashMap<>();
private Stack<Integer> circle = new Stack<>();
private Map<Integer, Boolean> onStack = new HashMap<>();
public Set<Integer> getPoints() {
Set<Integer> points = neighbors.keySet().stream().collect(Collectors.toCollection(HashSet::new));
this.neighbors.values().forEach(i -> points.addAll(i));
return points;
}
public int size() {
return getPoints().size();
}
public long edgeSize() {
return neighbors.values().stream().collect(Collectors.summingLong(Set::size));
}
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 detectCircle() {
for(Integer s : neighbors.keySet()) {
if(!marked.contains(s)) {
dfs(s);
}
}
}
private void dfs(Integer v) {
if(hasCircle) return;
onStack.put(v, true);
marked.add(v);
if(neighbors.get(v) == null) {
onStack.put(v, false);
return;
}
for(Integer w : neighbors.get(v)) {
if(!marked.contains(w)) {
path.put(w, v);
dfs(w);
} else if(onStack.get(w)) {
path.put(w, v);
this.hasCircle = true;
for(Integer u = v; !path.get(u).equals(v); u = path.get(u)) {
this.circle.push(u);
}
circle.push(w);
}
}
onStack.put(v, false);
}
public static void main(String...args) {
Digraph g = new Digraph();
//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);
//form circles
g.addEdge(7, 5);
g.addEdge(17, 15);
g.detectCircle();
System.out.println("strict digraph {");
while(!g.circle.isEmpty()) {
System.out.println(g.circle.pop() + "[color=red];");
}
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("hasCircle = " + g.hasCircle);
}
}