题目:
给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了a→b你就不能从b→a)空就是没有下一个结点了。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target
JAVA解答:
class Solution {
public LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> allPaths = new LinkedList<List<Integer>>();
public void dfs(int next, int target, int[][] graph) {
if(next == target) {
path.add(target);
LinkedList<Integer> tempPath = new LinkedList<>();
tempPath.addAll(path);
allPaths.add(tempPath);
path.removeLast();
return;
} else {
if(graph[next].length == 0) {
return;
} else {
path.add(next);
for(int i = 0; i < graph[next].length; i++) {
dfs(graph[next][i], target, graph);
}
path.removeLast();
}
}
}
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
if(graph.length == 0 || graph.length == 1) {
return null;
}
for(int i = 0; i < graph[0].length; i++) {
path.add(0);
dfs(graph[0][i], graph.length-1, graph);
// path.clear();
path.removeLast();
}
return allPaths;
}
}