代码随想录算法训练营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;
    }
}
相关推荐
Mephisto.java14 分钟前
【力扣 | SQL题 | 每日四题】力扣613, 579, 578, 580, 585
算法·leetcode
zhouzhurong43 分钟前
C语言scanf用%d读入字符型变量,通过输入字符的ASCII码输入字符
c语言·开发语言·算法
李元中1 小时前
2024下半年软考中级软件设计师,这100题,必做!
java·开发语言·javascript·人工智能·算法·ecmascript
疑惑的杰瑞2 小时前
[数据结构]带头双向循环链表的实现与应用
c语言·数据结构·算法·链表
Liu_Junwei3 小时前
回溯算法解决排列组合及子集问题
数据结构·算法
xiao_fwuu3 小时前
LeetCode 120. 三角形最小路径和
算法·leetcode·职场和发展
黎明smaly3 小时前
【数据结构与算法初阶】前言介绍
c语言·开发语言·数据结构·算法
single5944 小时前
【优选算法】(第十八篇)
java·数据结构·c++·vscode·算法·leetcode
视觉人机器视觉4 小时前
爸妈总说着学门技术,学机器视觉技术确实是一条踏实的生活道路,这条路你走得下去走得通吗?
人工智能·算法·计算机视觉·c#·自动化
学步_技术4 小时前
自动驾驶系列—从IMU到惯性定位算法:自动驾驶精准定位的幕后科技
科技·算法·自动驾驶·imu·惯性测量单元