DFS 主要用于查找图中的循环,而不是 BFS。有什么理由吗?两者都可以查找节点是否已经存在
遍历树/图时访问过。
深度优先搜索比广度优先搜索更节省内存,因为您可以更快地回溯。如果使用调用堆栈,实现起来也更容易,但这依赖于不会溢出堆栈的最长路径。
Also if your graph is directed http://en.wikipedia.org/wiki/Directed_graph then you have to not just remember if you have visited a node or not, but also how you got there. Otherwise you might think you have found a cycle but in reality all you have is two separate paths A->B but that doesn't mean there is a path B->A.
For example,
![](https://i.stack.imgur.com/lZ7ro.png)
如果你从0
,它会检测到存在循环,但实际上不存在循环。
通过深度优先搜索,您可以在下降时将节点标记为已访问,并在回溯时取消标记。请参阅有关此算法的性能改进的评论。
For the 检测有向图中循环的最佳算法 https://stackoverflow.com/questions/261573/best-algorithm-for-detecting-cycles-in-a-directed-graph你可以看看塔里安算法 http://en.wikipedia.org/wiki/Tarjan%E2%80%99s_strongly_connected_components_algorithm.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)