所有可能的路径 dfs
题目:所有可能的路径
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
leetcode:https://leetcode-cn.com/problems/all-paths-from-source-to-target/
class Solution: def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]: ans = [] stack = [] def dfs(s): n = graph.__len__() if s == n - 1: ans.append(stack[:]) return for i in graph[s]: stack.append(i) dfs(i) stack.pop() stack.append(0) dfs(0) return ans

浙公网安备 33010602011771号