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

不羁的心 提交于 2019-12-13 21:24:23

问题


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

回答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.



来源:https://stackoverflow.com/questions/20227745/code-for-cycle-detection-is-not-finding-returning-the-right-number-of-cycles-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!