邻接矩阵表示图
#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;
}