I have code written for calculating the no of cycles in a directed graph using DFS
. The method to check if a cycle exists or not works fine. I now iterate through all the vertices (which I have in a HashMap) and check if a vertex is unvisited, then check if a cycle exists, if so increment the counter by 1. Now the code breaks, it does not give the right number of cycles eg: for the graph with following edges:
(A B),(B C),(C E),(E A),(B E)
Here is my code;
public int getTotalCyclesinDir(){
clearAll();
int count=0;
for (Vertex v : vertexMap.values()) {
if (!v.isVisited && isCyclicDirected(v))
count++;
}
return count;
}
public boolean isCyclicDirected(Vertex v){
if (!v.isVisited){
v.setVisited(true);
Iterator<Edge> e = v.adj.iterator();
while (e.hasNext()){
Vertex t = e.next().target;
if (!t.isVisited) {
if (isCyclicDirected(t))
return true;
}
else return true;
}
return false;
}
else return true;
}
There are at least two problems with your algorithm:
isCyclicDirected
just detects whether there is any cycle in the graph. You can't use it directly to count cycles. For instance, your algorithm will count two cycles in (A B) (B A) (C A) because (C A) connects to a visited node.
If you want to detect two cycles in your example, your detection needs to be edge based instead of vertex based. (B E) forms a cycle but both B and E are marked visited from previous runs.