0

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;
}
Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
brain storm
  • 30,124
  • 69
  • 225
  • 393

1 Answers1

1

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.

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
  • I see your point. 1) what you mean by edge based, can you elaborate a little 2) in `isCyclicDirected` method, I have too many returns, is that all necessary or any room for simplification..Thanks – brain storm Nov 26 '13 at 22:34
  • Assume there is a river and you want to count bridges. You start on one side of the bridge and mark the shore as visited. Then you cross the bridge and mark the other side as visited. Then you conclude that there is only one bridge because you have visited both sides. – Stefan Haustein Nov 26 '13 at 23:06
  • I made changes to code and implemented differently to keep track of edges. Still I have some issues, which I posted here..http://stackoverflow.com/questions/20253255/couting-back-edges-to-get-the-number-of-cylces-in-a-directed-graph – brain storm Nov 27 '13 at 21:19