import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
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 reached;
private Integer goal;
private Integer start;
private int count;
private Integer[] edgeTo;
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 dfsPath(Integer start) {
this.edgeTo = new Integer[this.size()];
this.start = start;
dfs(start);
}
public void dfs(Integer v) {
marked.add(v);
if(neighbors.get(v) == null) return;
for(Integer w : neighbors.get(v)) {
if(!marked.contains(w)) {
edgeTo[w] = v;
dfs(w);
}
}
}
private void bfs(Integer start) {
this.edgeTo = new Integer[this.size()];
this.start = start;
Queue<Integer> queue = new LinkedList<>();
marked.add(start);
queue.add(start);
while(!queue.isEmpty()) {
Integer v = queue.poll();
if(neighbors.get(v) == null) return;
for(Integer w : neighbors.get(v)) {
if(!marked.contains(w)) {
marked.add(w);
edgeTo[w] = v;
queue.add(w);
}
}
}
}
private void printPath(Integer end) {
if(!marked.contains(end)) {
System.out.println("//not reachable point " + end);
return;
}
Stack<Integer> stack = new Stack<>();
for(Integer i = end; !i.equals(start); i = edgeTo[i]) {
stack.push(i);
}
stack.push(start);
Integer i = stack.pop();
while(!stack.isEmpty()) {
Integer j = stack.pop();
System.out.println(i +"->" + j + "[label=" + (count++) + ", color=red,penwidth=3.0];");
i = j;
}
}
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);
System.out.println("strict digraph {");
g.neighbors.keySet().stream().forEach(i ->
{
Stream.of(g.neighbors.get(i)).flatMap(j -> j.stream())
.forEach(k -> System.out.println(i + "->" + k + ";"));
});
//change the start point and goal point here
//g.dfsPath(3);
g.bfs(3);
g.printPath(6);
//g.bfsGoalSearch(3, 6);
System.out.println("}");
System.out.println("number of points: " + g.size());
System.out.println("number of edges: " + g.edgeSize());
}
}