LeetCode 797:所有路径从源出发 | DFS
LeetCode 797:所有路径从源出发 | DFS
引言
所有路径从源出发(All Paths From Source)是 LeetCode 第 797 题,难度为 Medium。题目要求找出从源节点到目标节点的所有路径。
算法实现
def allPathsSourceTarget(graph): target = len(graph) - 1 result = [] def dfs(node, path): if node == target: result.append(path[:]) return for neighbor in graph[node]: path.append(neighbor) dfs(neighbor, path) path.pop() dfs(0, [0]) return result复杂度分析
时间复杂度:O(V + E)
空间复杂度:O(V)
总结
DFS 遍历图,记录路径。
