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;
    }
};
相关推荐
To_OC3 小时前
LC 1 两数之和:面试第一道必考题,暴力解法直接被面试官 pass
javascript·算法·leetcode
鱼鱼不愚与8 小时前
《原来如此 | 第01期:为什么导航软件能预测红绿灯倒计时?》
算法
博客180011 小时前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴12 小时前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
复杂网络12 小时前
论最小 Agent 计算机的形态
算法
kisshyshy1 天前
🍦 雪糕、食堂、火车厢:三幅漫画吃透栈、队列与链表
javascript·算法
众少成多积小致巨1 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
猿人谷1 天前
不只是 CPU 阈值:STAR 如何用 GAT + Transformer 做容器级自动扩缩容?
人工智能·算法
复杂网络2 天前
Stable Diffusion 视觉大模型微调技术深度调研
算法