代码随想录算法训练营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;
    }
}
相关推荐
CoovallyAIHub15 小时前
是什么支撑L3自动驾驶落地?读懂AI驾驶与碰撞预测
深度学习·算法·计算机视觉
玉树临风ives15 小时前
atcoder ABC436 题解
c++·算法·leetcode·atcoder·信息学奥赛
patrickpdx15 小时前
leetcode:相等的有理数
算法·leetcode·职场和发展
dragoooon3415 小时前
[C++——lesson29.数据结构进阶——「AVL树」]
算法
碧海银沙音频科技研究院15 小时前
论文写作word插入公式显示灰色解决办法
人工智能·深度学习·算法
长沙京卓15 小时前
【无人机算法】低空经济下无人机巡检检测识别算法(城市、林业、水利)
算法·无人机
hn小菜鸡15 小时前
LeetCode 1971.寻找图中是否存在路径
算法·leetcode·职场和发展
Han.miracle15 小时前
数据结构与算法--007三数之和(medium)
算法·leetcode·排序算法
听风吹等浪起15 小时前
机器学习算法:随机梯度下降算法
人工智能·深度学习·算法·机器学习
落羽的落羽15 小时前
【C++】哈希扩展——位图和布隆过滤器的介绍与实现
linux·服务器·开发语言·c++·人工智能·算法·机器学习