代码随想录算法训练营第五十天|图论part1

98. 所有可达路径

题目链接: 98. 所有可达路径

文章讲解: 代码随想录

输入输出格式:

头文件

#include <iostream>

cin>>x;(给x,所以是向着x的)

cout<< x;(x给别人,所以是向着out的)

深度搜索三部曲:

1.确定参数

2.确定终止条件

3.处理当前节点逻辑

cpp 复制代码
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>>ans;
vector<int>path;
void dfs(vector<vector<int>>graph,int start,int end){
    if(start==end){               //终止条件
        ans.push_back(path);
        return;
    }
    for(int i=1;i<=end;i++){
        if(graph[start][i]==1){
            path.push_back(i);
            dfs(graph,i,end);    //递归
            path.pop_back();     //回溯
        }
    }
}

int main(){
    int n,m,s,t;
    cin>>n>>m;
    vector<vector<int>>graph(n+1,vector<int>(n+1,0));
    while(m--){
        cin>>s>>t;
        graph[s][t]=1;
    }
    path.push_back(1);
    dfs(graph,1,n);
    if (ans.size() == 0) cout << -1 << endl;
    for(const vector<int> &p:ans){
        for(int i=0;i<p.size()-1;i++){
            cout<<p[i]<<' ';
        }
        cout<<p[p.size()-1]<<endl;
    }
}
相关推荐
椰萝Yerosius9 分钟前
[题解]2024CCPC郑州站——Z-order Curve
c++·算法
小曹要微笑12 分钟前
STM32F7 时钟树简讲(快速入门)
c语言·stm32·单片机·嵌入式硬件·算法
南山安21 分钟前
栈(Stack):从“弹夹”到算法面试题的进阶之路
javascript·算法·面试
2301_764441331 小时前
Python构建输入法应用
开发语言·python·算法
AI科技星1 小时前
为什么变化的电磁场才产生引力场?—— 统一场论揭示的时空动力学本质
数据结构·人工智能·经验分享·算法·计算机视觉
TheLegendMe2 小时前
贪心+线程安全单例
算法·哈希算法
前端世界3 小时前
float 还是 double?用储罐体积计算带你看懂 C 语言浮点数的真实世界坑
java·c语言·开发语言
豐儀麟阁贵3 小时前
8.5在方法中抛出异常
java·开发语言·前端·算法
胖咕噜的稞达鸭3 小时前
算法入门:滑动窗口--->找到字符串中所有的字母异位词,串联所有的子串,最小覆盖子串
数据库·redis·算法
小青龙emmm3 小时前
2025级C语言第二次周测(国教专用)题解
c语言·开发语言·算法