为什么用 DFS 而不是 BFS 在图中寻找循环

编程入门 行业动态 更新时间:2024-10-05 13:22:17
本文介绍了为什么用 DFS 而不是 BFS 在图中寻找循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

主要使用 DFS 来查找图中的循环,而不是 BFS.有什么原因吗?两者都可以找到一个节点是否已经在遍历树/图时访问过.

Predominantly DFS is used to find a cycle in graphs and not BFS. Any reasons? Both can find if a node has already been visited while traversing the tree/graph.

推荐答案

深度优先搜索比广度优先搜索的内存效率更高,因为您可以更快地回溯.如果使用调用堆栈也更容易实现,但这依赖于不溢出堆栈的最长路径.

Depth first search is more memory efficient than breadth first search as you can backtrack sooner. It is also easier to implement if you use the call stack but this relies on the longest path not overflowing the stack.

此外,如果您的图表是

如果你从0开始做BFS,它会检测为存在循环但实际上没有循环.

If you do BFS starting from 0, it will detect as cycle is present but actually there is no cycle.

使用深度优先搜索,您可以在下降时将节点标记为已访问,并在回溯时取消标记.有关此算法的性能改进,请参阅评论.

With a depth first search you can mark nodes as visited as you descend and unmark them as you backtrack. See comments for a performance improvement on this algorithm.

对于检测有向图中循环的最佳算法你可以看看Tarjan的算法.

更多推荐

为什么用 DFS 而不是 BFS 在图中寻找循环

本文发布于:2023-11-29 15:30:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646804.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图中   什么用   而不是   DFS   BFS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!