这个python代码是否采用深度优先搜索(DFS)来查找所有路径?
作者:互联网
此代码在python official essays on graph theory中给出.这是代码:
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图中的子兄弟概念联系起来来解释代码?谢谢.
解决方法:
看到它是DFS的关键是递归发生在路径的累积之前.换句话说,在将任何内容放在“路径”列表之前,递归将尽可能深入.在返回列表之前,所有最深的兄弟姐妹都会积累在“路径”上.
我相信代码是正确的“附加”而不是“扩展”,因为“路径”是所有路径的累加器.虽然它可能写成
paths += find_all_paths(graph, node, end, path)
(编辑)……而不是
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
标签:depth-first-search,python,graph-theory 来源: https://codeday.me/bug/20191008/1873345.html