[英]Iterative into Recursive
大家好,我忙于做作业,想问一个问题。 我的目标是找到starter(start)和target(end)节点之间的所有可能路由。 我正在研究此代码及其图形: 注意:字典中的值显示键的邻居。
import sys
graph={'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'], 'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in graph:
return None
paths = []
for node in graph[start]:
if node not in path:
try:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
except TypeError:
print("No road")
sys.exit()
return paths
我希望这是一个完全递归的函数(应该没有“ for”循环)。我尝试了很多事情,但是每次都失败了。 你有什么建议吗?
您可以使用深度优先搜索来安全地浏览图形。 这使用了递归,并避免了使用marked
映射的无限循环:
marked = {}
def navigate(graph):
v, *tail = graph
iterate(v, tail) # recursive for loop replacement
def iterate(v, elements):
if v is not None:
if v not in marked:
dfs(graph, v)
if len(elements) > 0:
v, *tail = elements
iterate(v, tail)
def dfs(graph, v):
print(v) # do something with the node
marked[v] = True
w, *tail = graph[v]
iterate_edges(w, graph[v])
def iterate_edges(w, elements):
if w is not None:
if w not in marked:
dfs(graph, w)
if len(elements) > 0:
v, *tail = elements
iterate(v, tail)
graph = {'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'],
'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}
navigate(graph)
老实说,我更喜欢带有一些循环的实现,因为这样代码更易读:
marked = {}
def navigate(graph):
for v in graph:
if v not in marked:
dfs(graph, v)
def dfs(graph, v):
print (v)
marked[v] = True
for w in graph[v]:
if w not in marked:
dfs(graph, w)
graph = {'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'],
'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']}
navigate(graph)
两种变体的输出为:
x1
x2
x4
x5
x7
x9
x3
x6
x8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.