题目描述:
给一个有 n 个结点的有向无环图,找到所有从 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]]
解题:
1.深度优先搜索
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> paths = new ArrayList<>();
if (graph == null || graph.length == 0) {
return paths;
}
dfs(graph, 0, new ArrayList<>(), paths); //深度优先搜索
return paths;
}
public void dfs(int[][] graph, int node, List<Integer> path, List<List<Integer>> paths){
path.add(node); //入栈(List)
if(node == graph.length-1){ //如果已经走到头
paths.add(new ArrayList<>(path)); //将栈(List)中的元素添加进paths
return;
}
for(int nextNode: graph[node]){
dfs(graph, nextNode, path, paths); //递归调用
path.remove(path.size()-1); //出栈(List)
}
}
}
2.广度优先搜索
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> paths = new ArrayList<>();
if (graph == null || graph.length == 0) {
return paths;
}
Queue<List<Integer>> queue = new LinkedList<>();
List<Integer> path = new ArrayList<>();
path.add(0);
queue.add(path);
while ( queue.size() > 0 ) {
int levelSize = queue.size();
List<Integer> currentPath = queue.poll(); //当前路径出队列
int node = currentPath.get(currentPath.size() - 1);
for (int nextNode: graph[node]) { //遍历当前路径的下一个节点
List<Integer> tmpPath = new ArrayList<>(currentPath);
tmpPath.add(nextNode); //将下一个节点并入当前路径
if (nextNode == graph.length - 1) { //如果走到头了
paths.add(new ArrayList<>(tmpPath)); //将该条路径加入paths
} else {
queue.add(new ArrayList<>(tmpPath)); //将新路径入队列
}
}
}
return paths;
}
}