代码随想录算法训练营第五十天|图论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;
    }
}
相关推荐
焦耳加热2 小时前
阿德莱德大学Nat. Commun.:盐模板策略实现废弃塑料到单原子催化剂的高值转化,推动环境与能源催化应用
人工智能·算法·机器学习·能源·材料工程
wan5555cn2 小时前
多张图片生成视频模型技术深度解析
人工智能·笔记·深度学习·算法·音视频
u6063 小时前
常用排序算法核心知识点梳理
算法·排序
索迪迈科技5 小时前
基于野火F407开发板实现电源管理-停止模式
c语言·stm32·单片机·嵌入式硬件·mcu
蒋星熠5 小时前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
小莞尔5 小时前
【51单片机】【protues仿真】基于51单片机宠物投食系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小欣加油5 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
3Cloudream5 小时前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
王璐WL6 小时前
【c++】c++第一课:命名空间
数据结构·c++·算法
空白到白6 小时前
机器学习-聚类
人工智能·算法·机器学习·聚类