递归是一种编程技术,它允许函数调用自身来解决问题。在图论或树形结构中,递归常用于遍历所有可能的路径。当我们需要找到从源节点到目标节点的所有路径时,递归是一种有效的方法。
递归可以分为两种主要类型:
递归在以下场景中非常有用:
以下是一个Python示例,展示如何使用递归方式存储从源到目标的所有路径:
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if start not in graph:
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
# 示例图
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['E'],
'D': ['E'],
'E': ['F'],
'F': []
}
# 查找从 'A' 到 'F' 的所有路径
paths = find_all_paths(graph, 'A', 'F')
print(paths)
import sys
sys.setrecursionlimit(10000) # 增加栈大小
def find_all_paths(graph, start, end, path=[], memo={}):
if (start, end) in memo:
return memo[(start, end)]
path = path + [start]
if start == end:
return [path]
if start not in graph:
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path, memo)
for newpath in newpaths:
paths.append(newpath)
memo[(start, end)] = paths
return paths
通过这些方法,可以有效地解决递归过程中遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云