深搜啪的一下就完事了。
一开始想用广搜,后来发现还得自定义class,太麻烦了。
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
final List<List<Integer>> ans = new LinkedList<>();
final Deque<Integer> list = new LinkedList<>();
int aim = graph.length - 1;
list.add(0);
dfs(0, aim, graph, list, ans);
return ans;
}
void dfs(int now, int aim, int[][] graph, Deque<Integer> list, List<List<Integer>> ans) {
if(now == aim) {
ans.add(new LinkedList<>(list));
return;
}
for (int i : graph[now]) {
list.add(i);
dfs(i, aim, graph, list, ans);
list.removeLast();
}
}
}

这篇博客探讨了一种使用深度优先搜索(DFS)算法来查找图中从源节点到目标节点的所有路径的方法。作者最初考虑使用广度优先搜索(BFS),但由于需要自定义类而转向了深搜,最终实现了一个简洁的解决方案。代码中展示了如何通过DFS遍历图,并将找到的路径存储在结果列表中。
1105

被折叠的 条评论
为什么被折叠?



