题目
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。
译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a 。
示例
示例1
输入: graph = [[1,2],[3],[3],[]]
输出: [[0,1,3],[0,2,3]]
解释: 有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
示例2
输入: graph = [[4,3,1],[3,2,4],[3],[4],[]]
输出: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
示例3
输入: graph = [[1],[]]
输出: [[0,1]]
示例4
输入: graph = [[1,2,3],[2],[3],[]]
输出: [[0,1,2,3],[0,2,3],[0,3]]
示例5
输入: graph = [[1,3],[2],[3],[]]
输出: [[0,1,2,3],[0,3]]
关键思路
使用动态规划的方法。
需要注意的是,本题为找到所有可能的路径,而非找到单一路径,所以我设计的动态规划表,维护了所有经过起点的路线,以方便更新和查找。
代码实现
class Solution(object):
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
dp = [ [0] ] # set a dp table
for i in range(len(graph)): # number of nodes
for path in dp: # check the end of the current path
if path[-1] == i:
for suf in graph[i]:
dp.append(path+[suf])
return [ p for p in dp if p[-1] == len(graph)-1 ]
if __name__ == "__main__":
graph = input()
obj = Solution()
result = obj.allPathsSourceTarget(graph)
print(result)
运行结果
[[0, 1, 3],[0, 2, 3]]
[[0, 4], [0, 1, 4], [0, 3, 4], [0, 1, 3, 4], [0, 1, 2, 3, 4]]
[[0, 1]]
[[0, 3], [0, 2, 3], [0, 1, 2, 3]]
[[0, 3], [0, 1, 2, 3]]
链接
https://leetcode-cn.com/problems/all-paths-from-source-to-target