算法训练营64-图论-深度优先优先搜索(dfs)-广度优先搜索(bfs)

题目:98. 所有可达路径 (kamacoder.com)

邻接矩阵表示图

复制代码
#include<bits/stdc++.h>

using namespace std;

vector<vector<int>> reslut;
vector<int> path;

void dfs(vector<vector<int>>& map, int start, int end) {
    if(start == end) {
        reslut.push_back(path);
        return;
    }
    for(int i = 1;i < map.size();i++) {
        if(map[start][i] == 1) {
            path.push_back(i);
            dfs(map, i, end);
            path.pop_back();
        }
    }
}


int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> map(n + 1, vector<int>(n + 1, 0));
    for(int i = 0;i < m;i++) {
        int x,y;
        cin >> x >> y;
        map[x][y] = 1;
    }
    path.push_back(1);
    dfs(map, 1, n);
    if(reslut.size() == 0) cout << -1 << endl;
    else {
        for(int i = 0;i < reslut.size();i++) {
            for(int j = 0;j < reslut[i].size() - 1;j++) {
                cout << reslut[i][j] << ' ';
            }
            cout << reslut[i][reslut[i].size() - 1] << endl;
        }
    }
    return 0;
}

邻接表表示图:

复制代码
#include <iostream>
#include <vector>
#include <list>
  
using namespace std;
  
vector<vector<int>> result;
vector<int> path;
  
void dfs(vector<list<int>>& map, int x, int n) {
    if(x == n) {
        result.push_back(path);
        return;
    }
    for(int i : map[x]) {
        path.push_back(i);
        dfs(map, i, n);
        path.pop_back();
    }
}
   
int main() {
    int n, m, x, y;
    cin >> n >> m;
    
    vector<list<int>> graph(n + 1);
    while(m--) {
        cin >> x >> y;
        graph[x].push_back(y);
    }
    path.push_back(1);
    dfs(graph, 1, n);
    if(result.size() == 0) cout << -1 << endl;
    else {
        for(int i = 0;i < result.size();i++) {
            int size = result[i].size();
            for(int j = 0;j < size - 1;j++) {
                cout << result[i][j] << ' ';
            }
            cout << result[i][size - 1] << endl;
        }        
    }
 
    return 0;
}
相关推荐
@小码农20 分钟前
2025年北京海淀区中小学生信息学竞赛第一赛段试题(附答案)
人工智能·python·算法·蓝桥杯
2301_7951672021 分钟前
玩转Rust高级应用 如何让让运算符支持自定义类型,通过运算符重载的方式是针对自定义类型吗?
开发语言·后端·算法·安全·rust
laocooon52385788625 分钟前
C语言 有关指针,都要学哪些内容
c语言·数据结构·算法
多多*1 小时前
牛客周赛 Round 114 Java题解
算法
他们叫我一代大侠1 小时前
Leetcode :模拟足球赛小组各种比分的出线状况
算法·leetcode·职场和发展
Nebula_g1 小时前
C语言应用实例:硕鼠游戏,田忌赛马,搬桌子,活动选择(贪心算法)
c语言·开发语言·学习·算法·游戏·贪心算法·初学者
AI科技星2 小时前
张祥前统一场论动量公式P=m(C-V)误解解答
开发语言·数据结构·人工智能·经验分享·python·线性代数·算法
海琴烟Sunshine2 小时前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode
geobuilding2 小时前
将大规模shp白模贴图转3dtiles倾斜摄影,并可单体化拾取建筑
算法·3d·智慧城市·数据可视化·贴图
jghhh012 小时前
基于高斯伪谱法的弹道优化方法及轨迹仿真计算
算法