所有可达路径
文章链接:https://programmercarl.com/kamacoder/0098.所有可达路径.html#本题代码
题目链接:https://kamacoder.com/problempage.php?pid=1170
#include <iostream>
#include <vector>
using namespace std;//全局路径
vector<vector<int>> paths;
vector<int> path;void dfs(vector<vector<int>> graph,vector<bool> &visited,int x,int n){//递归结束条件if(x==n){paths.push_back(path);return;}for(int i=1;i<=n;i++){if(graph[x][i]==1&&visited[i]==false){path.push_back(i);visited[i]=true;dfs(graph,visited,i,n);visited[i]=false;//回溯path.pop_back();//回溯}}
}int main(){int n,m;cin>>n>>m;//创建n*n的邻接矩阵vector<vector<int>> graph(n+1,vector<int>(n+1,0));vector<bool> visited(n+1,false);while(m--){int s,t;cin>>s>>t;graph[s][t]=1;}//一开始就已经从节点1开始了,故这里初始化path,和visited[1]path.push_back(1);visited[1]=true;dfs(graph,visited,1,n);// 输出结果if (paths.size() == 0) cout << -1 << endl;for (const vector<int> &pa : paths) {for (int i = 0; i < pa.size() - 1; i++) {cout << pa[i] << " ";}cout << pa[pa.size() - 1] << endl;}}
总结:这里在随想录中没有将会形成环的路径排除,所以我加了一个visited数组,用来记录已经访问过的节点。