代码随想录算法训练营day50

1.所有可达路径

1.1 题目

https://kamacoder.com/problempage.php?pid=1170

1.2 题解

复制代码
#include <iostream>
#include <vector>
#include <list>
using namespace std;


//收集结果数组
vector<vector<int>> result;
//单个路径
vector<int> path;
//递归函数,x代表当前遍历的节点,n代表终点节点
void dfs(vector<vector<int>>& graph, int x, int n)
{
    //确定终止条件
    if (x == n)
    {
        result.push_back(path);
        return;
    }
    //遍历节点x连接的所有节点
    for (int i = 1; i <= n; i++)
    {
        if (graph[x][i] == 1)
        {
            path.push_back(i);
            dfs(graph, i, n);
            path.pop_back();
        }
    }

}


int main()
{


    int nodes;
    int margins;
    cin >> nodes >> margins;
    int s;
    int t;
    //构造邻接矩阵
    vector<vector<int>> graph(nodes + 1, vector<int>(nodes + 1, 0));
    for (int i = 0; i < margins; ++i)
    {
        cin >> s >> t;
        //存储
        graph[s][t] = 1;
    }
    path.push_back(1);
    dfs(graph, 1, nodes);
    // 输出结果
    if (result.size() == 0) cout << -1 << endl;
    for (const vector<int>& pa : result) {
        for (int i = 0; i < pa.size() - 1; i++) {
            cout << pa[i] << " ";
        }
        cout << pa[pa.size() - 1] << endl;
    }
}
相关推荐
happymaker062628 分钟前
LeetCodeHot100——155.最小栈
算法
洛水水38 分钟前
【力扣100题】85.每日温度
算法·leetcode·职场和发展
Coder-magician43 分钟前
《代码随想录》刷题打卡day15:二叉树part05
数据结构·c++·算法
Kurisu_红莉栖43 分钟前
力扣56合并区间
算法·leetcode
Irissgwe1 小时前
算法的时间复杂度和空间复杂度
数据结构·c++·算法·c·时间复杂度·空间复杂度
随意起个昵称1 小时前
区间dp-基础题目3(永别)
c++·算法
周末也要写八哥1 小时前
有向图Hierholzer算法的另一种实现
算法
bIo7lyA8v1 小时前
算法调优中的性能回归与基准测试分析的技术8
算法·数据挖掘·回归
有点。1 小时前
C++贪心算法二(练习题)
c++·算法·贪心算法
西安邮电大学1 小时前
贪心算法详细讲解
java·后端·其他·算法·面试