代码随想录算法训练营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;
    }
}
相关推荐
Han.miracle4 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8246 小时前
前后缀分解
算法
你好,我叫C小白6 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林9 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway9 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No79 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区10 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫10 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展
liu****10 小时前
8.list的模拟实现
linux·数据结构·c++·算法·list
地平线开发者10 小时前
征程 6 | 征程 6 工具链如何支持 Matmul/Conv 双 int16 输入量化?
算法·自动驾驶