图的构建及打印
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAX_V = 100;
vector<vector<int>> adj(MAX_V);
void AddEdge(int from, int to) {
adj[from].push_back(to);
adj[to].push_back(from);
}
void Print(const vector<int>& prev, int s, int t) {
if (prev[t] != -1 && t != s) {
Print(prev, s, prev[t]);
}
cout << t << " ";
}
dfs
bool found = false;
void RecurDfs(int cur, int t, vector<bool>& visited, vector<int>& prev) {
if (found) {
return;
}
visited[cur] = true;
if (cur == t) {
found = true;
return;
}
for (size_t i = 0; i < adj[cur].size(); i++) {
int q = adj[cur][i];
if (!visited[q]) {
prev[q] = cur;
RecurDfs(q, t, visited, prev);
}
}
}
void Dfs(int s, int t) {
const int kV = 3;
vector<bool> visited(kV, false);
vector<int> prev(kV, -1);
RecurDfs(s, t, visited, prev);
Print(prev, s, t);
}
int main(int argc, char** argv) {
AddEdge(0, 1);
AddEdge(0, 2);
AddEdge(1, 2);
Dfs(0, 2);
return 0;
}
输出:0 1 2
bfs
void Bfs(int s, int t) {
if (s == t) {
return;
}
const int kV = 3;
vector<bool> visited(kV, false);
vector<int> prev(kV, -1);
visited[s] = true;
queue<int> q;
q.push(s);
while (!q.empty()) {
int cur = q.front();
q.pop();
for (size_t i = 0; i < adj[cur].size(); i++) {
int p = adj[cur][i];
if (!visited[p]) {
prev[p] = cur;
if (p == t) {
Print(prev, s, t);
return;
}
visited[p] = true;
q.push(p);
}
}
}
}
int main(int argc, char **argv) {
AddEdge(0, 1);
AddEdge(0, 2);
AddEdge(1, 2);
Bfs(0, 2);
return 0;
}
输出:0 2