给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号节点所能到达的下一些节点,空就是没有下一个结点了。
/*
一个典型的搜索案例,深度搜索,即一条路走到黑,不通再返回上一个节点寻找新路。不停的尝试和反馈的过程。
*/
class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
Deque<Integer> df = new ArrayDeque<Integer>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
df.offerLast(0);
dfs(graph,0,graph.length - 1);
return ans;
}
public void dfs(int[][] graph, int a, int n){
if(a == n){
ans.add(new ArrayList<Integer>(df));
return;
}
for(int y:graph[a]){
df.offerLast(y);
dfs(graph,y,n);
df.pollLast();
}
}
}
/*
BFS:将一个节点的所有情况都遍历一遍,存放在栈中。放入记录放入纪律,扩散。
*/
class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
Queue<List<Integer>> df = new LinkedList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
df.add(new ArrayList<>(){{add(0);}});
while(!df.isEmpty()){
List<Integer> path = df.remove();
int node = path.get(path.size() - 1);
if(node == graph.length - 1){
ans.add(path);
continue;
}
for(int y:graph[node]){
List<Integer> y_path = new ArrayList<>(path);
y_path.add(y);
df.add(y_path);
}
}
return ans;
}
}