1.12 力扣中等图论

797. 所有可能的路径 - 力扣(LeetCode)

给你一个有 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]]

思路:

使用dfs深度优先算法,从起点0开始遍历当前可去节点有哪些,直到走到终点target

递归函数参数

当前节点cur,终点target,图信息graph,当前path经过节点记录,当前路径curPath,最后结果ret

cpp 复制代码
    void dfs(int cur,int target,vector<vector<int>>& graph,unordered_set<int>& setPath,vector<int>& curPath,vector<vector<int>>& ret)

递归终止条件:cur==target

递归内容:

循环进入当前节点可去的节点,寻找可行方案

cpp 复制代码
        for(int e:graph[cur])
        {
            if(setPath.count(e)) continue;

            setPath.insert(e);
            curPath.push_back(e);
            dfs(e,target,graph,setPath,curPath,ret);
            setPath.erase(e);
            curPath.pop_back();
        }
cpp 复制代码
class Solution {
public:
    void dfs(int cur,int target,vector<vector<int>>& graph,unordered_set<int>& setPath,vector<int>& curPath,vector<vector<int>>& ret)
    {
        if(cur==target)
        {
            ret.push_back(curPath);
            return;
        }
        for(int e:graph[cur])
        {
            if(setPath.count(e)) continue;

            setPath.insert(e);
            curPath.push_back(e);
            dfs(e,target,graph,setPath,curPath,ret);
            setPath.erase(e);
            curPath.pop_back();
        }
        return;
    }
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        int target=graph.size()-1;//终点
        unordered_set<int> setPath;
        vector<int> curPath;
        //加入起点
        curPath.push_back(0);
        setPath.insert(0);

        vector<vector<int>> ret;
        dfs(0,target,graph,setPath,curPath,ret);
        return ret;
    }
};
相关推荐
先做个垃圾出来………13 分钟前
偏移量解释
数据结构·算法
Dream it possible!15 分钟前
LeetCode 面试经典 150_链表_旋转链表(64_61_C++_中等)
c++·leetcode·链表·面试
FanXing_zl19 分钟前
基于整数MCU的FOC控制定标策略深度解析
单片机·嵌入式硬件·mcu·算法·定点运算·q15
立志成为大牛的小牛33 分钟前
数据结构——三十三、Dijkstra算法(王道408)
数据结构·笔记·学习·考研·算法·图论
地平线开发者1 小时前
mul 与 reduce_sum 的优化实例
算法·自动驾驶
坚持编程的菜鸟2 小时前
LeetCode每日一题——Pow(x, n)
c语言·算法·leetcode
csdn_aspnet2 小时前
分享MATLAB在数据分析与科学计算中的高效算法案例
算法·matlab·数据分析
白云千载尽2 小时前
moveit使用和机器人模型与状态--正向运动学和逆向运动学分析(四)
算法·机器人·逆运动学·moveit·正向运动学
我想吃余2 小时前
【0基础学算法】前缀和刷题日志(三):连续数组、矩阵区域和
算法·矩阵·哈希算法
2501_938773993 小时前
文档搜索引擎搜索模块迭代:从基础检索到智能语义匹配升级
人工智能·算法·搜索引擎