javagraphdepth-first-searchdirected-graphcyclic-graph

code for cycle detection is not finding returning the right number of cycles in directed graph in Java?


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;
}

Solution

  • There are at least two problems with your algorithm: