参考:1.https://labuladong.gitee.io/algo/di-yi-zhan-da78c/shou-ba-sh-03a72/tu-lun-ji--d55b2/
2.代码随想录图论 (qq.com)
例题1:所有可能路径(考察图的遍历)
给你一个有 n
个节点的 有向无环图(DAG),请你找出所有从节点 0
到节点 n-1
的路径并输出(不要求按特定顺序) graph[i]
是一个从节点 i
可以访问的所有节点的列表(即从节点 i
到节点 graph[i][j]
存在一条有向边)。
输入:graph = [[1,2],[3],[3],[]] 输出:[[0,1,3],[0,2,3]] 解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
注:注意回溯参数(图,节点),此外本题是无环图,不需要使用visited数组
class Solution:def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:result = []path = []last = len(graph) - 1def backtrack(graph,x):if x == last:result.append(path[:])returnfor i in range(0, len(graph[x])):path.append(graph[x][i])backtrack(graph,graph[x][i])path.pop()path.append(0)backtrack(graph, 0)return result