我試圖在C++中實現BFS,函數應該像這樣工作:以一個頂點爲參數的圖形&,然後創建兩個向量,其中一個用於存儲與參數頂點相鄰的頂點,然後檢查那些頂點,如果其中一個未被訪問,則獲取它的鄰接點並將它們添加到向量中,然後頂點應被標記爲VISITED並打印;我寫了這段代碼,但它輸出了任何內容。注:我確保其他功能&像圖這樣的數據結構正在工作,問題在於BFS功能,我希望你們中的一些人能幫我解決它。如何實現廣度優先搜索?
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
enum Mark {VISITED, UNVISITED};
struct Vertex {
char name;
Mark mark;
};
struct Edge{
Vertex v1;
Vertex v2;
Edge(Vertex vertex1, Vertex vertex2): v1(vertex1), v2(vertex2){};
};
struct Graph{
vector<Vertex>vertices;
vector<Edge>edges;
vector<pair<Vertex, Edge>> adjacent(char u){
vector<pair<Vertex, Edge>>res;
for(Edge e : edges){
if(e.v1.name == u){
res.push_back(make_pair(e.v2, e));
}else if(e.v2.name == u){
res.push_back(make_pair(e.v1, e));
}
}
return res;
}
vector<Vertex> getAdj(char u){
vector<Vertex>result;
for(Edge e: edges){
if(e.v1.name == u){
result.push_back(e.v2);
}else if(e.v2.name == u){
result.push_back(e.v1);
}
}
return result;
}
};
void BFS(Graph g, Vertex u){
vector<Vertex>vec = g.getAdj(u.name);
for(Vertex v : vec){
if(v.mark == UNVISITED){
vector<Vertex>q = g.getAdj(v.name);
for(int i=0; i<q.size(); i++){
vec.push_back(q[i]);
}
v.mark = VISITED;
vec.pop_back();
cout << v.name << " ";
}
}
}
int main(int argc, const char * argv[]) {
Graph g;
Vertex v1, v2, v3, v4, v5, v6;
v1.name = 'A';
v2.name = 'B';
v3.name = 'C';
v4.name = 'D';
v5.name = 'E';
v6.name = 'Z';
g.edges.push_back(Edge(v1, v2));
g.edges.push_back(Edge(v1, v3));
g.edges.push_back(Edge(v2, v3));
g.edges.push_back(Edge(v2, v4));
g.edges.push_back(Edge(v3, v4));
g.edges.push_back(Edge(v3, v5));
g.edges.push_back(Edge(v4, v5));
g.edges.push_back(Edge(v4, v6));
g.edges.push_back(Edge(v5, v6));
BFS(g, v1);
cout << endl;
}
感謝您的回答,它幫助我輸出了一些東西,但仍然存在bfs算法問題, – Salma
您知道它應該給出什麼輸出嗎? – ShadowMitia
@Salma我已更新我的回答 – ShadowMitia