卡码网98 所有可达路径
深搜+邻接矩阵写法
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> ans;
string path = "1";
void dfs(vector<vector<int>>& grid, int index, int n) {
if (index == n) {
ans.push_back(path);
return;
}
for (int i = 1; i <= n; i++) {
if (grid[index][i] == 1) {
string temp = path;
path += " ";
path += to_string(i);
dfs(grid, i, n);
path = temp;
}
}
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int>> grid(n+1, vector<int>(n+1,0));
while (m--) {
int a, b;
cin >> a >> b;
grid[a][b] = 1;
}
dfs(grid, 1, n);
if (ans.size() == 0) {
cout << -1 << endl;
return 0;
}
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << endl;
}
}
深搜+邻接表写法
#include <iostream>
#include <list>
#include <vector>
#include <string>
using namespace std;
vector<string> ans;
string path = "1";
void dfs(vector<list<int>>& l, int index, int n) {
if (index == n-1) {
ans.push_back(path);
return;
}
for (int i : l[index]) {
string temp = path;
path += " ";
path += to_string(i+1);
dfs(l, i, n);
path = temp;
}
}
int main() {
int n, m;
cin >> n >> m;
vector<list<int>> l(n);
int s, t;
for (int i = 0; i < m; i++) {
cin >> s >> t;
l[s-1].push_back(t-1);
}
dfs(l, 0, n);
if (ans.size() == 0) {
cout << -1 << endl;
return 0;
}
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << endl;
}
}
这题用广搜会比较麻烦一点,要记录路径,在深搜中我们可以用递归逻辑来实现,广搜就是迭代法,我们不能再只用一个变量path记录所有的路径再存入,而是要一次性用vector数组记录对应的路径,并且要再过程中新增路径条数。