今天入门图论的基本理论,做了深度优先遍历图的例子
797.所有可能的路径
解题过程
- 用dfs遍历每一个边
力扣
class Solution {
public:
vector<vector<int>>result;
vector<int>path;
void dfs(vector<vector<int>>& graph) {
if (path.back() == graph.size() - 1) {
result.push_back(path);
return;
}
int points = path.back();
for (int point : graph[points]) {
path.push_back(point);
dfs(graph);
path.pop_back();
}
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
path.push_back(0);
dfs(graph);
return result;
}
};
ACM
#include<iostream>
#include<vector>
#include<list>
using namespace std;
int n, m;
vector<vector<int>>result;
vector<int>path;
void dfs(vector<list<int>>&graph) {
if (path.back() == n) {
result.push_back(path);
return;
}
int point = path.back();
for (int i : graph[point]) {
path.push_back(i);
dfs(graph);
path.pop_back();
}
}
int main() {
cin >> n >> m;
vector<list<int>>graph(n + 1);
while (m--) {
int s, t;
cin >> s >> t;
graph[s].push_back(t);
}
path.push_back(1);
dfs(graph);
if (result.size() == 0) cout << -1 << endl;
for (vector<int>vec : result) {
for (int i = 0; i < vec.size() - 1; i++) {
cout << vec[i] << " ";
}
cout << vec.back() << endl;
}
}