用C++实现无向图。要求:1、建立一个用邻接表表示的无向图。 2、对上边无向图进行广度优先遍历
时间: 2024-05-06 11:17:38 浏览: 74
以下是C++实现无向图(邻接表表示)和广度优先遍历的代码:
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Graph {
private:
int V; // 顶点数
vector<int> *adj; // 邻接表
public:
Graph(int V) {
this->V = V;
adj = new vector<int>[V];
}
void addEdge(int v, int w) {
adj[v].push_back(w);
adj[w].push_back(v);
}
void BFS(int s) {
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
queue<int> q;
visited[s] = true;
q.push(s);
while (!q.empty()) {
int v = q.front();
cout << v << " ";
q.pop();
for (auto i = adj[v].begin(); i != adj[v].end(); ++i) {
if (!visited[*i]) {
visited[*i] = true;
q.push(*i);
}
}
}
cout << endl;
}
};
int main() {
Graph g(5);
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
cout << "BFS starting from vertex 2:" << endl;
g.BFS(2);
return 0;
}
```
输出结果为:
```
BFS starting from vertex 2:
2 1 3 4 0
```
其中,图的顶点数为5,边的情况如下:
```
0----1
|\ | \
| \ | \
| \ | \
| \| \
4----3----2
```
广度优先遍历的起点为2,输出遍历结果。
阅读全文