find all path
Wed Sep 11 2024 19:31:10 GMT+0000 (Coordinated Universal Time)
Saved by
@LizzyTheCatto
#include <iostream>
#include <vector>
#include <deque>
#include <algorithm>
using namespace std;
// FAP nghĩa là find all path
void FAP(int A, int B, vector<vector<int>>& S){
deque<vector<int> > dq;
vector<vector<int>> all;
dq.push_back({A});
while (!dq.empty()) {
vector<int> path = dq.front();
dq.pop_front();
int end = path.back();
if (end == B) {
all.push_back(path);
} else {
for (int i = 0; i < S[end].size(); i++) {
int nei = S[end][i];
if (find(path.begin(), path.end(), nei) == path.end()) {
vector<int> newpath = path;
newpath.push_back(nei);
dq.push_back(newpath);
}
}
}
}
// In tất cả các đường đi tìm được
cout << "Tất cả các đường đi từ " << A << " đến " << B << ":\n";
for (const auto& p : all) {
for (int i = 0; i < p.size(); i++) {
cout << p[i];
if (i < p.size() - 1) cout << " -> ";
}
cout << endl;
}
}
int main() {
int n, m;
cin >> n >> m;
vector<vector<int> > S(n + 1); // Sử dụng vector 2D để lưu đồ thị
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
S[u].push_back(v);
S[v].push_back(u); // Đồ thị vô hướng
}
int A, B; // Đỉnh bắt đầu A và đỉnh đích B
cin >> A >> B;
FAP(A, B, S);
return 0;
}
content_copyCOPY
https://www.programiz.com/cpp-programming/online-compiler/
Comments