力扣 797. 所有可能路径【DFS】

1. 题目

2. 代码

  • DFS , 直接见代码
cpp 复制代码
class Solution {
public:
    vector<int> path;
    vector<vector<int>> res;    // 结果集
    void dfs(vector<vector<int>>& graph, int cur, int n){
        // 找出所有从节点 0 到节点 n-1 的路径
        // 下标从 0 开始的
        if (cur == n){  // 当前点到了终点
            // 说明找到了一条路径, 收集起来
            res.push_back(path);
            // 返回
            return ;
        }
        // 当前节点下面有什么边连着
        for (const auto& cc : graph[cur]){
            path.push_back(cc); // 收集这个节点
            // 沿着这条路径递归
            dfs(graph, cc, n);
            path.pop_back();    // 回溯
        }
        return ;
    }
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
        // dfs
        // 邻接表
        // 从第一个节点出发
        path.push_back(0);
        dfs(graph, 0, graph.size() - 1);
        return res;

    }
};
相关推荐
hhzz7 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_7 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI8 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅
atunet8 小时前
关于图算法中的连通分量检测与最小割问题7
算法
心运软件8 小时前
银行客户流失预测(Python 完整实战)
算法
邪神与厨二病8 小时前
牛客周赛 Round 153
python·算法
qizayaoshuap10 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
皓月斯语11 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet11 小时前
树状结构在查询优化中的作用与实现细节7
算法
徐凤年_12 小时前
rog_map参数理解
算法