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;
    }
};
相关推荐
heimeiyingwang9 天前
【深度学习加速探秘】Winograd 卷积算法:让计算效率 “飞” 起来
人工智能·深度学习·算法
LyaJpunov9 天前
深入理解 C++ volatile 与 atomic:五大用法解析 + 六大高频考点
c++·面试·volatile·atomic
小灰灰搞电子9 天前
Qt PyQt与PySide技术-C++库的Python绑定
c++·qt·pyqt
时空自由民.9 天前
C++ 不同线程之间传值
开发语言·c++·算法
ai小鬼头9 天前
AIStarter开发者熊哥分享|低成本部署AI项目的实战经验
后端·算法·架构
小白菜3336669 天前
DAY 37 早停策略和模型权重的保存
人工智能·深度学习·算法
zeroporn9 天前
以玄幻小说方式打开深度学习词嵌入算法!! 使用Skip-gram来完成 Word2Vec 词嵌入(Embedding)
人工智能·深度学习·算法·自然语言处理·embedding·word2vec·skip-gram
Ray_19979 天前
C++二级指针的用法指向指针的指针(多级间接寻址)
开发语言·jvm·c++
亮亮爱刷题9 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
_周游9 天前
【数据结构】_二叉树OJ第二弹(返回数组的遍历专题)
数据结构·算法