代码随想录算法训练营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;
    }
}
相关推荐
Dlrb121122 分钟前
C语言-指针数组与数组指针
c语言·数据结构·算法·指针·数组指针·指针数组·二级指针
WL_Aurora24 分钟前
Python 算法基础篇之集合
python·算法
平行侠36 分钟前
A15 工业路由器IP前缀高速检索与内存压缩系统
网络·tcp/ip·算法
阿旭超级学得完2 小时前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
li星野2 小时前
位运算 & 数学 & 高频进阶九题通关(Python + C++)
c++·python·学习·算法
jerryinwuhan2 小时前
hello算法,简单讲(1)
算法·排序算法
y = xⁿ2 小时前
20天速通LeetCodeday15:BFS广度优先搜索
算法·宽度优先
400分2 小时前
吃透RAG核心-----语义检索与关键字检索底层原理
算法·架构
目黑live +wacyltd2 小时前
算法备案:常见驳回原因与应对策略
人工智能·算法
磊 子3 小时前
多态类原理+四种类型转换+异常处理
开发语言·c++·算法