我正在尝试进行深度优先搜索以查找所有路径的列表,然后确定最短和最长的路径。
Python文档(https://www.python.org/doc/essays/graphs/)中提到了以下内容,需要一个结束节点:
我的问题是如何在(有向无环)图中找到所有路径,而不需要指定结束节点?我的起始节点始终保持不变。
我可以在开始时使用for循环来迭代节点。但这似乎不是最有效的方法,因为我可能会使用相同的路径重新访问一个节点,这将浪费计算时间。
Python文档(https://www.python.org/doc/essays/graphs/)中提到了以下内容,需要一个结束节点:
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:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
我的问题是如何在(有向无环)图中找到所有路径,而不需要指定结束节点?我的起始节点始终保持不变。
我可以在开始时使用for循环来迭代节点。但这似乎不是最有效的方法,因为我可能会使用相同的路径重新访问一个节点,这将浪费计算时间。
for node in nodeList:
find_all_paths(graph, 0, node)