【发布时间】:2021-06-30 23:08:31
【问题描述】:
我做了一个递归 DFS 算法,它可以在找到目标时返回路径。请注意,我正在利用递归,并尝试在路径保存中使用尽可能少的内存。当找到目标时,保证path 将包含正确的路径。但是随后 DFS 必须完全停止,否则由于之后的pop()s,我无法返回正确的列表。临时解决方案是全局列表result。有什么办法:
- 找到目标后停止递归?
- 在指定点返回
path列表?
result = []
def dfs(graph, vertex, visited, path):
global result
if vertex not in visited:
visited.add(vertex)
if isTarget(vertex):
print("Solution found ! " + str(path))
result = path.copy() # recursion must stop here and return path at this state
for neighbor in graph.getSuccessors(vertex):
path.append(neighbor[1]) #neighbor[1] is direction
print("Visiting node" + str(neighbor[0]))
dfs(graph, neighbor[0], visited, path)
path.pop()
【问题讨论】:
-
你试过把
else放在最后for之前吗? -
@testing_22 是的,没有区别。
标签: python algorithm recursion search depth-first-search