写的比较乱,也不完善,后续再慢慢加:
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <cassert>
using namespace std;
class Graph{
public:
Graph(int num) : n(num), m(0), adj(vector<vector<int>>(num, vector<int>())){}
void addEdge(int s, int t){
assert(s >= 0 && s < n);
assert(t >= 0 && t < n);
adj[s].push_back(t);
adj[t].push_back(s);
++m;
}
bool hasEdeg(int s, int t){
assert(s >= 0 && s < n);
assert(t >= 0 && t < n);
for(const auto &val : adj[s]){
if(val == t) return true;
}
return false;
}
void bfs(int s, int t){//借助队列
if(s == t) return;
vector<bool> visited(n, false);//记录是否已访问
vector<int> prev(n, -1);//保存遍历路径(反向存储的)
visited[s] = true;
queue<int> q;
q.push(s);
while(!q.empty()){
int v = q.front();
q.pop();
for(const auto &w : adj[v]){//遍历节点v的邻接节点
if(!visited[w]){//如果该节点没有被访问过
prev[w] = v;//记录路径
if(w == t){//bfs结束,输出路径
print(prev, s, t);
return;
}
visited[w] = true;//置位
q.push(w);
}
}
}
}
void dfs(int s, int t){//借助栈
vector<bool> visited(n, false);
vector<int> prev(n, -1);
visited[s] = true;
stack<int> stk;
stk.push(s);
while(!stk.empty()){
int v = stk.top();
stk.pop();
for(const auto &w : adj[v]){
if(!visited[w]){
prev[w] = v;
if(w == t){
print(prev, s, t);
return;
}
visited[w] = true;
stk.push(w);
}
}
}
}
void print(vector<int> &prev, int s, int t){//prev为反向存储,这儿递归打印
if(prev[t] != -1 && s != t){
print(prev, s, prev[t]);
}
cout << t << " ";
}
private:
int n, m;//n为节点个数,m为边的条数
vector<vector<int>> adj;
};
main.cpp:
#include "graph.h"
int main(){
int vertex, edge;
cout << "请输入顶点数和边数:" << endl;
cin >> vertex >> edge;
Graph my_graph(vertex);
for(int i = 0; i < edge; ++i){
int from, to;
cin >> from >> to;
my_graph.addEdge(from, to);
}
int s, t;
cout << "请输入搜索起点与终点:" << endl;
cin >> s >> t;
my_graph.bfs(s, t);
cout << endl;
my_graph.dfs(s, t);
cout << endl;
return 0;
}