中等
相关标签
给你一个有 n 个节点的 有向无环图(DAG),请你找出所有从节点 0 到节点 n-1 的路径并输出(不要求按特定顺序)
graph[i] 是一个从节点 i 可以访问的所有节点的列表(即从节点 i 到节点 graph[i][j]存在一条有向边)。
示例 1:

输入:graph = [[1,2],[3],[3],[]] 输出:[[0,1,3],[0,2,3]] 解释:有两条路径 0 -> 1 -> 3 和 0 -> 2 -> 3
示例 2:

输入:graph = [[4,3,1],[3,2,4],[3],[4],[]] 输出:[[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
提示:
n == graph.length2 <= n <= 150 <= graph[i][j] < ngraph[i][j] != i(即不存在自环)graph[i] 中的所有元素 互不相同
vector和> result; vector:这两个成员变量分别用来收集符合条件的路径和存储当前节点0到终点的路径。path;
void dfs (vector:这是一个递归函数,用于进行深度优先搜索。参数>& graph, int x) graph表示当前的图,x表示目前遍历的节点。在
dfs函数中,首先判断当前节点是否为终点,如果是则将当前路径path加入到结果集合result中;否则遍历当前节点连接的所有节点,将其加入路径中,然后递归调用dfs函数进行下一层遍历,最后需要撤销当前节点,即回溯操作。
vector:这是一个公开的接口函数,用于开始整个遍历过程。在这个函数中,首先将起始节点0加入到路径中,然后调用> allPathsSourceTarget(vector >& graph) dfs函数开始深度优先搜索,最终返回结果集合result。
O(2^m)
间复杂度取决于图的结构和节点之间的连接关系。假设有n个节点,m条边,那么在最坏情况下,时间复杂度为O(2^m),因为在DFS过程中,我们会探索所有可能的路径。
O(2^m)
空间复杂度方面,主要消耗的是存储结果集合
result和当前路径path所需的空间。在最坏情况下,可能会有指数级的路径数量,因此空间复杂度也是指数级别的,即O(2^m)。
- class Solution {
- public:
- vector
int>> result; // 用于存储符合条件的路径集合 - vector<int> path; // 用于存储当前经过的路径节点
-
- // 深度优先搜索函数
- // x:当前遍历的节点
- // graph:当前的图
- void dfs (vector
int >>& graph, int x) { - // 寻找从节点 0 到节点 n-1 的路径,即graph.size() - 1
- if (x == graph.size() - 1) { // 找到一条符合条件的路径
- result.push_back(path); // 将当前路径加入结果集合
- return;
- }
- for (int i = 0; i < graph[x].size(); i++) { // 遍历节点x连接的所有节点
- path.push_back(graph[x][i]); // 将遍历到的节点加入路径中
- dfs(graph, graph[x][i]); // 递归进入下一层搜索
- path.pop_back(); // 回溯,撤销当前节点
- }
- }
-
- // 寻找从节点0到终点的所有路径
- vector
int>> allPathsSourceTarget(vectorint>>& graph) { - path.push_back(0); // 起始节点为0
- dfs(graph, 0); // 开始深度优先搜索
- return result; // 返回结果集合
- }
- };
- // 深度优先遍历
- class Solution {
- List
> ans; // 用来存放满足条件的路径
- List
cnt; // 用来保存 dfs 过程中的节点值 -
- public void dfs(int[][] graph, int node) {
- if (node == graph.length - 1) { // 如果当前节点是 n - 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(graph, nextNode); // 递归深度优先搜索下一个节点
- cnt.remove(cnt.size() - 1); // 回溯,撤销当前节点,尝试其他分支
- }
- }
-
- public List
> allPathsSourceTarget(int[][] graph) {
- ans = new ArrayList<>(); // 初始化结果集合
- cnt = new ArrayList<>(); // 初始化当前路径
- cnt.add(0); // 注意,0 号节点要加入 cnt 数组中作为起点
- dfs(graph, 0); // 开始深度优先搜索
- return ans; // 返回结果
- }
- }
觉得有用的话可以点点赞,支持一下。
如果愿意的话关注一下。会对你有更多的帮助。
每天都会不定时更新哦 >人< 。