0797. 所有可能的路径【中等】
1. 📝 题目描述
给你一个有 n 个节点的 有向无环图(DAG),请你找出从节点 0 到节点 n-1 的所有路径并输出(不要求按特定顺序)
graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。
示例 1:

txt
输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 31
2
3
2
3
示例 2:

txt
输入: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]]1
2
2
提示:
n == graph.length2 <= n <= 150 <= graph[i][j] < ngraph[i][j] != i(即不存在自环)graph[i]中的所有元素 互不相同- 保证输入为 有向无环图(DAG)
2. 🎯 s.1 - DFS
c
void dfs(int** graph, int* graphColSize, int n, int node, int* path, int pathLen, int*** res, int* resSize, int** resColSize) {
if (node == n - 1) {
(*res)[*resSize] = (int*)malloc(sizeof(int) * pathLen);
memcpy((*res)[*resSize], path, sizeof(int) * pathLen);
(*resColSize)[*resSize] = pathLen;
(*resSize)++;
return;
}
for (int i = 0; i < graphColSize[node]; i++) {
path[pathLen] = graph[node][i];
dfs(graph, graphColSize, n, graph[node][i], path, pathLen + 1, res, resSize, resColSize);
}
}
int** allPathsSourceTarget(int** graph, int graphSize, int* graphColSize, int* returnSize, int** returnColumnSizes) {
int maxPaths = 1 << (graphSize - 1);
int** res = (int**)malloc(sizeof(int*) * maxPaths);
*returnColumnSizes = (int*)malloc(sizeof(int) * maxPaths);
*returnSize = 0;
int* path = (int*)malloc(sizeof(int) * graphSize);
path[0] = 0;
dfs(graph, graphColSize, graphSize, 0, path, 1, &res, returnSize, returnColumnSizes);
free(path);
return res;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
js
/**
* @param {number[][]} graph
* @return {number[][]}
*/
var allPathsSourceTarget = function (graph) {
const res = []
const n = graph.length
const dfs = (node, path) => {
if (node === n - 1) {
res.push([...path])
return
}
for (const next of graph[node]) {
path.push(next)
dfs(next, path)
path.pop()
}
}
dfs(0, [0])
return res
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
py
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
res = []
n = len(graph)
def dfs(node: int, path: list):
if node == n - 1:
res.append(path[:])
return
for nxt in graph[node]:
path.append(nxt)
dfs(nxt, path)
path.pop()
dfs(0, [0])
return res1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- 时间复杂度:
,路径数最多为 ,每条路径长度最多为 n - 空间复杂度:
,递归栈深度
算法思路:
- 由于是有向无环图,直接从节点 0 开始 DFS
- 到达节点 n-1 时记录当前路径,回溯探索所有可能的路径