Finding all cycles in a directed graph using recursive backtracking

会有一股神秘感。 提交于 2019-12-01 00:13:55

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