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;
    }
};
相关推荐
能源系统预测和优化研究7 分钟前
【原创代码改进】考虑共享储能接入的工业园区多类型负荷需求响应经济运行研究
大数据·算法
yoke菜籽21 分钟前
LeetCode——三指针
算法·leetcode·职场和发展
小高不明1 小时前
前缀和一维/二维-复习篇
开发语言·算法
bin91531 小时前
当AI优化搜索引擎算法:Go初级开发者的创意突围实战指南
人工智能·算法·搜索引擎·工具·ai工具
SoveTingღ1 小时前
【问题解析】我的客户端与服务器交互无响应了?
服务器·c++·qt·tcp
温宇飞2 小时前
内存异常
c++
曹牧2 小时前
Java:Math.abs()‌
java·开发语言·算法
CoovallyAIHub3 小时前
纯视觉的终结?顶会趋势:不会联觉(多模态)的CV不是好AI
深度学习·算法·计算机视觉
CoovallyAIHub3 小时前
一文读懂大语言模型家族:LLM、MLLM、LMM、VLM核心概念全解析
深度学习·算法·计算机视觉
范纹杉想快点毕业3 小时前
嵌入式C语言实战开发详解
linux·运维·算法