1、前言

2、思路
这题的表示形式类似于图的领接表的表示方法,数组里存储相邻的节点。
这一题并没有说出现环的情况,且需要求的是遍历过程的路径,所以解法类似于回溯的解法,只不过回溯是遍历树,这边是遍历图。但是树其实也算图,所以他们遍历节点的方式非常类似。
3、代码
public class AllPathsSourceTarget {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
dfs(graph, 0, new LinkedList<>());
return res;
}
private void dfs(int[][] graph, int value, LinkedList<Integer> path) {
path.add(value);
int n = graph.length;
if(value == n - 1){
res.add(new LinkedList<>(path));
path.removeLast();
return;
}
for (int i : graph[value]) {
dfs(graph, i, path);
}
path.removeLast();
}
public static void main(String[] args) {
int[][] graph = {{1, 2}, {3}, {3}, {}};
List<List<Integer>> paths = new AllPathsSourceTarget().allPathsSourceTarget(graph);
for (List<Integer> path : paths) {
for (Integer integer : path) {
System.out.print(integer + " ");
}
System.out.println();
}
}
}
网友评论