#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;
}
测试效果图:
测试结果: