当前位置: 首页 > news >正文

km98. 所有可达路径(邻接矩阵+邻接表)

邻接矩阵

#include <cstdio>
#include <vector>
#include <iostream>

static std::vector<std::vector<int>> result;
static std::vector<int> path;

void dfs(std::vector<std::vector<int>>& graph, int x, int n) {
    if(x == n) {
        result.push_back(path);
        return;
    }
    for(int i = 1; i <= n; i++) {
        if(graph[x][i]) {
            path.push_back(i);
            dfs(graph, i, n);
            path.pop_back();
        }
    }
}

int main() {
    int n, m;
    std::cin >> n >> m;
    std::vector<std::vector<int>> graph(n + 1, std::vector<int>(n + 1, 0));
    for(int i = 0; i < m; i++) {
        int a, b;
        std::cin >> a >> b;
        graph[a][b] = 1;
    }
    path.push_back(1);
    dfs(graph, 1, n);
    if(result.size() == 0) std::cout << -1 << std::endl;
    else {
        for(auto p : result) {
            for(int i = 0; i < p.size() - 1; i++) std::cout << p[i] << " ";
            std::cout << p[p.size() - 1] << std::endl;
        }
    }
    
    return 0;
}

邻接表

#include <cstdio>
#include <iostream>
#include <vector>
#include <list>

static std::vector<int> path;
static std::vector<std::vector<int>> result;

void dfs(const std::vector<std::list<int>>& graph, int cur, const int n) {
    if(cur == n) {
        result.push_back(path);
        return;
    }
    
    for(auto it = graph[cur].begin(); it != graph[cur].end(); it++) {
        path.push_back(*it);
        dfs(graph, *it, n);
        path.pop_back();
    }
    
}

int main() {
    int n;  // n个节点
    int m;  // m条边
    std::cin >> n >> m;
    std::vector<std::list<int>> graph(n + 1);
    for(int i = 0; i < m; i++) {
        int a, b;
        std::cin >> a >> b;
        graph[a].push_back(b);
    }
    
    path.push_back(1);
    dfs(graph, 1, n);
    
    if(result.size() == 0) std::cout << -1 << std::endl;
    else {
        for(auto p : result) {
            for(int i = 0; i < p.size() - 1; i++) {
                std::cout << p[i] << " ";
            }
            std::cout << p[p.size() - 1] << std::endl;
        }
    }
    
    return 0;
}

相关文章:

  • 【02】Cocos游戏开发引擎从0开发一款游戏-cocos项目目录结构熟悉-调试运行项目-最重要的assets资源文件认识-场景sense了解-优雅草卓伊凡
  • 953 验证外星语词典
  • Qt关于平滑滚动的使用QScroller及QScrollerProperties类说明
  • 228页PPT丨制造业核心业务流程优化咨询全案(战略营销计划生产研发质量),附核心系统集成架构技术支撑体系,2月26日资料已更新
  • 【博资考1】网安学院-北航网安数学基础部分
  • Tomcat介绍
  • 13、虚函数和纯虚函数的区别【高频】
  • vscode+vue前端开发环境配置
  • YOLOv11-ultralytics-8.3.67部分代码阅读笔记-model.py
  • C++ 二分法中向下取整与向上取整的区别与应用场景详解
  • DeepSeek在赋能客户服务方面,3大业务场景落地
  • 【cuda学习日记】5.2 共享内存数据分布
  • 哔哩哔哩IT私塾python爬虫视频教程中的项目文件
  • python绘制cox列线图及绘制指南
  • Halcon 学习之路 set_grayval 算子
  • c++stl——容器
  • C++Qt学习笔记——实现一个串口通信界面
  • Debian安装C语言环境
  • DeepSeek开源:FlashMLA深度解析:Hopper架构上的大模型推理革命
  • 重大更新!锂电池剩余寿命预测新增 CALCE 数据集
  • 在本轮印巴冲突的舆论场上也胜印度一筹,巴基斯坦靠什么?
  • 龚正市长调研闵行区,更加奋发有为地稳增长促转型,久久为功增强发展后劲
  • 车建兴被留置:跌落的前常州首富和红星系重整迷路
  • 董军在第六届联合国维和部长级会议上作大会发言
  • 为什么越来越多景区,把C位留给了书店?
  • 深圳拟出让3宗居住用地,共计用地面积6.77公顷