Finding all cycles in a directed graph using recursive backtracking

前端 未结 1 1845
[愿得一人]
[愿得一人] 2021-01-03 08:36

I am working on finding cycles in directed graph using recursive backtracking. There is a suggested pseudocode for this here, which is here:

dfs(adj,node,vis         


        
相关标签:
1条回答
  • 2021-01-03 08:56

    For (1 2),(2 3),(3 1), you're calling:

    • dfs(vertex1, vertex1, count), which gives you the cycle 1 -> 2 -> 3 -> 1.
    • dfs(vertex2, vertex2, count), which gives you the cycle 2 -> 3 -> 1 -> 2.
    • dfs(vertex3, vertex3, count), which gives you the cycle 3 -> 1 -> 2 -> 3.

    So you're counting the same cycle multiple times.

    The simplest fix I can think of is simply setting the visited flag after the dfs call.

    public int allCyclesDirectedmain(){
        clearAll();
        int[] count = new int[1];
        for (Vertex v: vertexMap.values()){
            dfs(v,v,count);
            v.setVisited(true); // <---
        }
        return count[0];
    }
    
    0 讨论(0)
提交回复
热议问题