Python DFS 和 BFS
这里 http://www.python.org/doc/essays/graphs/ 是DFS对吗?
我尝试与“兄弟姐妹”做一些事情,但它不起作用。 任何人都可以编写类似于此站点代码的 BFS。
Here http://www.python.org/doc/essays/graphs/ is DFS right ?
I try to do something with 'siblings', but it does not work.
Can anyone write BFS similar to code from this site.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,就是DFS。
要编写 BFS,您只需要保留一个“todo”队列。您可能还想将该函数转换为生成器,因为 BFS 通常会在生成所有可能的路径之前被故意终止。因此这个函数可以用作find_path或find_all_paths。
以及如何使用它的示例:
Yes, it is DFS.
To write a BFS you just need to keep a "todo" queue. You probably also want to turn the function into a generator because often a BFS is deliberately ended before it generates all possible paths. Thus this function can be used to be find_path or find_all_paths.
And an example of how to use it:
这是一个 O(N * max(顶点度)) 广度优先搜索实现。 bfs 函数以广度优先顺序生成节点,并为每个节点生成一个可用于追踪回到起点的最短路径的生成器。路径的惰性本质意味着您可以迭代生成的节点来查找您感兴趣的点,而无需支付构建所有中间路径的成本。
Here's an O(N * max(vertex degree)) breadth-first search implementation. The bfs function generates nodes in breadth-first order, and for each a generator that can be used to trace a shortest path back to the start point. The lazy nature of the paths means that you can iterate through the generated node to find points you're interested in without paying the cost of building all the intermediate paths.