98. 所有可达路径
本文最后更新于587 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com

https://www.programmercarl.com/kamacoder/0098.%E6%89%80%E6%9C%89%E5%8F%AF%E8%BE%BE%E8%B7%AF%E5%BE%84.html

1.本题是图论的第一道题也是又一道ACM赛制的题,老实说做力扣的关键代码的题都有点看不懂本题给出的完整代码里的创建的容器和初始化的一些操作了,实际上自己的基础也确实是差一些,今天通过做这个题也是巩固了一下回溯算法,然后对dfs bfs有了更深刻的认知,然后就是对于邻接表和邻接矩阵的初始化和构造有了更深的认知,实话说要是让我在之前没有今天的了解让我构建这两个结构我大概率一头雾水呢,只能说要让自己不断的巩固这些知识,一直去写题,二刷三刷我相信会有结果。

CPP

#include<bits/stdc++.h>
using namespace std;

vector<vector<int>> res;
vector<int> path;

void dfs(const vector<vector<int>>& graph, int x, int n){
    if(x == n){
        res.push_back(path);
        return ;
    }
    
    for(int i = 1; i <= n; i++){
        if(graph[x][i] == 1){
            path.push_back(i);
            dfs(graph, i, n);
            path.pop_back();
        }
    }
//    for (int i : graph[x]) { // 找到 x指向的节点
//        path.push_back(i); // 遍历到的节点加入到路径中来
//        dfs(graph, i, n); // 进入下一层递归
//        path.pop_back(); // 回溯,撤销本节点
//    }
}


int main(){
    int m,n,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;
    }
// while (m--) {
//      cin >> s >> t;
//      // 使用邻接表 ,表示 s -> t 是相连的
//      graph[s].push_back(t);

//  }
    
    path.push_back(1);
    dfs(graph, 1, n);
    
    if(res.size() == 0)cout<< "-1"<<endl;
    for(const vector<int> &pa : res){
        for(int i = 0; i < pa.size() - 1; i++){
            cout<<pa[i]<<" ";
        }
        cout<<pa[pa.size() - 1]<<endl;
    }
    return 0;
    
}
文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇
Cream_dpl