我正在尝试进行深度优先搜索以查找所有路径的列表,然后确定最短和最长的路径。找到没有指定结束节点的所有路径?
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)