给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。
译者注:有向图是有方向的,即规定了 a→b 你就不能从 b→a 。
来源:力扣(LeetCode)
链接:所有可能的路径
示例 1:
输入:graph = [[1,2],[3],[3],[]]
输出:[[0,1,3],[0,2,3]]
解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
思路:
深度优先搜索:
- 从第一个节点出发,深度优先搜索出所有可能的路径,新建一个栈,将路径存放到栈中,然后判断是否成功,如果成功,则将栈中的路径记录下来
- 自设例子图解:
过程
0入栈
1入栈
1出栈
2入栈
3入栈
5入栈
5出栈
3出栈
4入栈
3入栈
5入栈
5出栈
3出栈
4出栈
6入栈:成功,此时栈的内容就是一条成功路径的倒序
代码:
class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
Deque<Integer> stack = new ArrayDeque<Integer>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
stack.offerLast(0);
dfs(graph, 0, graph.length - 1);
return ans;
}
public void dfs(int[][] graph, int x, int n) {
if (x == n) {
ans.add(new ArrayList<Integer>(stack));
return;
}
for (int y : graph[x]) {
stack.offerLast(y);
dfs(graph, y, n);
stack.pollLast();
}
}
}