本文最后更新于587 天前,其中的信息可能已经过时,如有错误请发送邮件到tomding1065@gmail.com
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;
}