C++实现邻接表存储的图及bfs遍历
生活随笔
收集整理的這篇文章主要介紹了
C++实现邻接表存储的图及bfs遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <iostream>
#include <queue>
using namespace std;
typedef char VerTexType;
#define MVNum 100
typedef char OtherInfo;
bool vis[MVNum];//鄰接表
typedef struct ArcNode {int adjvex;struct ArcNode *nextarc;OtherInfo info;
} ArcNode;//弧(邊)typedef struct VNode {VerTexType data;ArcNode *firstarc;
} VNode, AdjList[MVNum];//頂點typedef struct {AdjList vertices;int vexnum, arcnum;
} ALGraph;//圖int LocateVex(ALGraph G, int v) {//找點的下標for (int i = 0; i < G.vexnum; i++) {if (v == G.vertices[i].data)return i;}return -1;
}void CreateUDG(ALGraph &G) {//采用鄰接表創建無向圖cin >> G.vexnum >> G.arcnum;for (int i = 0; i < G.vexnum; i++) {cin >> G.vertices[i].data;G.vertices[i].firstarc = NULL;}int i, j;for (int k = 0; k < G.arcnum; k++) {VerTexType v1, v2;cin >> v1 >> v2;i = LocateVex(G, v1);j = LocateVex(G, v2);ArcNode *p1;//用頭插法插入p1 = new ArcNode;p1->adjvex = j;p1->nextarc = G.vertices[i].firstarc;G.vertices[i].firstarc = p1;ArcNode *p2;p2 = new ArcNode;//如果是有向圖,則不需要下面的代碼p2->adjvex = i;p2->nextarc = G.vertices[j].firstarc;G.vertices[j].firstarc = p2;}
}void BFS(ALGraph G, int v) {//用bfs遍歷cout << G.vertices[v].data;vis[v] = true;queue<int>q;q.push(v);while (q.size()) {ArcNode *t = G.vertices[q.front()].firstarc;q.pop();for (ArcNode *p = t; p; p = p->nextarc) {if (!vis[p->adjvex]) {vis[p->adjvex] = true;cout << G.vertices[p->adjvex].data;q.push(p->adjvex);}}}
}int main() {ALGraph G;CreateUDG(G);BFS(G, 0);return 0;
}
測試效果圖:
測試結果:
總結
以上是生活随笔為你收集整理的C++实现邻接表存储的图及bfs遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机械键盘脏了怎么清理?机械键盘清洗的详细
- 下一篇: 《C++ Primer》第一章的 Sal