Python深度优先搜索(包括循环)

编程入门 行业动态 更新时间:2024-10-06 06:44:28
本文介绍了Python深度优先搜索(包括循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我在StackOverflow中看到了以下有关Python中DFS算法的帖子(非常有用):

so i saw the following post in StackOverflow regarding DFS algorithm in Python(very helpful):

此python吗代码使用深度优先搜索(DFS)来查找所有路径?

我还有一个需要分析的图形(以找到两个节点之间的每条可能的路径),但是我还需要在其中包括周期.例如,如果我有一个这样的图形:

I also have a graph that need to analyze (to find every possible path between two nodes), but I need to include the cycles there also. For example, if I have a graph like this:

graph = {'Start': ['1'], '1': ['2'], '2': ['3','End'], '3': ['2','End']}

我想要以下输出:

Start, 1, 2, 3, End Start, 1, 2, End Start, 1, 2, 3, 2, End Start, 1, 2, 3, 2, 3, End

有没有办法更改以下代码来做到这一点?

Is there any possible way to change the following code in order to do this?

def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] if not graph.has_key(start): return [] paths = [] for node in graph[start]: if node not in path: paths += find_all_paths(graph, node, end, path) return paths print find_all_paths(graph, 'Start', 'End')

推荐答案

如注释中所述,如果允许任意循环,则算法没有理由终止.您可以做的是允许最大路径长度,并消除所有过长的路径:

As mentioned in the comment, your algorithm has no reason to terminate if you allow arbitrary cycles. What you could do is allow for a maximum path length and dismiss all paths that are too long:

def find_all_paths(graph, start, end, path=[], max_length=10): if len(path) >= max_length: return [] path = path + [start] if start == end: return [path] if start not in graph: return [] paths = [] for node in graph[start]: paths += find_all_paths(graph, node, end, path, max_length=max_length) return paths

graph = {'Start': ['1'], '1': ['2'], '2': ['3','End'], '3': ['2','End']} print find_all_paths(graph, 'Start', 'End', max_length=10)

您的算法打印:

[['Start', '1', '2', '3', '2', '3', '2', '3', '2', 'End'], ['Start', '1', '2', '3', '2', '3', '2', '3', 'End'], ['Start', '1', '2', '3', '2', '3', '2', 'End'], ['Start', '1', '2', '3', '2', '3', 'End'], ['Start', '1', '2', '3', '2', 'End'], ['Start', '1', '2', '3', 'End'], ['Start', '1', '2', 'End']]

编辑:

将 not graph.has_key 替换为更具Python风格的 start not in graph

Replaced not graph.has_key with the more pythonic start not in graph

更多推荐

Python深度优先搜索(包括循环)

本文发布于:2023-11-29 02:04:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:深度   Python

发布评论

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

>www.elefans.com

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