I have been writing code to get all the possible cycles in a directed graph. Here is an implementation that keeps track of back edges and whenever one back edge is found, it return true that one cycle is detected. I extended this to the following:
calculate all the possible back edges in a tree, the number of back edges should give the number of cycles. Not sure if this correct. using this, I implemented the following: The count
variable below is not useful. Initially I had it to give the count of each cycles. but that does not give the correct answer. but the size of edgeMap
that stores all the back edges seems to give the correct number of cycles in some graphs but not all.
The code works for G2 an G3 in the picture, but fails for G1. (G1 has only two cycles, but I get three back edges). any suggestions of where I could be going wrong will be helpful
public int allCyclesDirectedmain(){
clearAll();
int count=0;
Map<Vertex, Vertex> edgeMap = new HashMap<>();
for (Vertex v : vertexMap.values()) {
if (!v.isVisited && allCyclesDirected(v,edgeMap))
count++;
}
System.out.println(edgeMap);
return count;
}
public boolean allCyclesDirected(Vertex v, Map<Vertex, Vertex> edgeMap ){
if (!v.isVisited){
v.setVisited(true);
Iterator<Edge> e = v.adj.iterator();
while (e.hasNext()){
Vertex t = e.next().target;
if (!t.isVisited && allCyclesDirected(t,edgeMap)){
edgeMap.put(v, t);
return true;
}
else
return true;
}
}
return false;
}