// 深度优先遍历
class Solution {
List<List<Integer>> ans; // 用来存放满足条件的路径
List<Integer> cnt; // 用来保存 dfs 过程中的节点值
// 深度优先搜索方法,找出从当前节点到目标节点的所有路径
public void dfs(int[][] graph, int node) {
// 如果当前节点是目标节点,保存这条路径到结果列表中,然后返回
if (node == graph.length - 1) {
ans.add(new ArrayList<>(cnt));
return;
}
// 遍历当前节点的邻居节点
for (int index = 0; index < graph[node].length; index++) {
int nextNode = graph[node][index];
// 将邻居节点加入到路径中
cnt.add(nextNode);
// 递归调用DFS,继续向下遍历
dfs(graph, nextNode);
// 回溯,将最后加入到路径中的节点移除,继续探索其他路径
cnt.remove(cnt.size() - 1);
}
}
// 找出从源节点到目标节点的所有路径
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
ans = new ArrayList<>();
cnt = new ArrayList<>();
cnt.add(0); // 将起始节点加入到路径中
dfs(graph, 0); // 开始深度优先搜索
return ans; // 返回所有满足条件的路径列表
}
}
算法:所有可能的路径-图论基础,必会
最新推荐文章于 2024-03-30 21:37:04 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)