Is backtracking absolutely necessary for cycle detection using DFS in directed graph?

[亡魂溺海] 提交于 2019-12-06 11:26:22

Why you need to backtrack:

A -> B
^ \
|  v
D <- C

If you go A -> B and you don't backtrack, you'll stop there and you won't find the cycle.

Your algorithm does backtrack. You're just wrapping it in recursion so it might not quite look the way you expect. You recurse for one of the neighbours, if this doesn't find a cycle, that call returns and you try some other neighbour - this is backtracking.

Why you need to remember how you got to where you are:

A -> B
  \  ^
   v |
     C

The above graph has no cycle, but if you go A -> B, then A -> C -> B, you'll think there is if you don't remember the path.

As mentioned in the linked post, you can just set the visited flag to false before returning in your code (which I see you've now done) - this will act as remembering the path.

It's worth pointing out that this marking algorithm is an adaptation of the naive approach to linked list cycle detection that involves keeping track of each node visited so far. In this case the path followed by the recursion is treated as a linked list and the linked list algorithm is applied. The space complexity is what makes the algorithm sub-optimal for linked lists, since you need to hold a reference to each node in the list it is O(n). When you're applying this to a decently well-balanced graph howeever, the space complexity drops to O(logn). In the case where the graph is a tree, the space complexity degrades to O(n) but you get O(n) time complexity.

Also, the algorithm is still incorrect. Given a graph with nodes A and B and a single edge B->B, isCyclicDirected(A) will never detect the cycle.

backtracking is not essential only if your graph doesn't have any case where you can get from node A to node B by two different paths. Your algo will detect a false positive in the case mentioned in the previous answer: A -> B \ ^ v | C But if you add backtracking your alto will work perfectly, even in the case above.

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