我在'递归函数'中相当新.所以,我试图解决为什么我们使用递归函数以及递归函数如何工作,我想我对它有一个相当好的理解.
两天前,我试图解决最短路径问题.我有一个下面的图(它在python中):
graph = {'a': ['b', 'c'],
'b': ['c', 'd'],
'c': ['d'],
'd': ['c'],
'e': ['f'],
'f': ['c']}
Run Code Online (Sandbox Code Playgroud)
我只是想找到一条路,而不是最短路径.所以,这里是代码:
def find_path(graph,start,end,path=[]):
path = path + [start]
#Just a Test
print(path)
if start == end:
return path
if start not in graph:
return None
for node in graph[start]:
if node not in path:
new_path = find_path(graph,node,end,path)
if new_path:
#Just a test
print(path)
return new_path
print(find_path({'a':['b','c'],'b':['c','d'],'c':['d'],'d':['c'],'e':
['f'],'f':['c']},'a','d'))
Run Code Online (Sandbox Code Playgroud)
我的起始顶点是'a',结束顶点是'd'.
在第四行中,我只是打印了"路径"以查看路径的位置.
在第17行,我还打印了"路径",再次进行测试.这是结果:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', …Run Code Online (Sandbox Code Playgroud)