此代码在python official essays on graph theory中给出。这里的代码:这个Python代码是否使用深度优先搜索(DFS)来查找所有路径?
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
我不擅长python,因为我还没有足够的练习和阅读。您能否通过将此与DFS图中的同胞概念相关联来解释代码?谢谢。
'paths.extend(newpaths)' – 2010-11-20 02:25:59
作为参考,我总是会'不在图中开始而不是在'无图。 has_key(start)'(我假设'graph'是一个'dict'或类似的)。 – 2010-11-20 02:27:18
克里斯,是的'图'是一个'字典'。 – Pupil 2010-11-20 02:28:04