第797题. 所有可能的路径
参考题解:官方题解
题目:
标签:
- 深度优先遍历。
思路:
- 这道题思路是很简单的。而且是有向无环图,都不用考虑环了。这种题是面试必须要会的。
- 不过,这道题有一些 Java 语言的语法细节很有意思,如果不熟练可能会吃亏。
- 首先,Deque 的使用。Deque 我个人认为是比 Queue 更好用的类型,就是双端队列,左右两侧都可以添加和删除,实现类有 ArrayDeque 和 LinkedList,方法是 offerFirst、pollFirst、offerLast、pollLast。
- 其次,是 Collections 集合类内部的类型转换。例如 ArrayList 和 ArrayDeque 如何互相转换。可以直接类型强制转换就行,将原内容放到
new 新内容类型<数据类型>(原内容)
中的括号里面就可以了。 - 最后,递归可以采用
stack.offerLast(y); dfs(graph, y, n); stack.pollLast();
实现。
题解:
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();
}
}
}