#include <iostream> #include <queue> #define MaxSize 10 using namespace std; bool visited[MaxSize]; //全局数组,记录结点是否已补访问 typedef struct edgenode { //边表结点 int adjvex; //邻接点 int weight; //权值 edgenode *next; //下一条边 }; typedef struct vertexnode { //顶点结点 char data; //结点数据 edgenode *fist; //指向第一条边 }AdjList[MaxSize]; typedef struct AdjListGraph { AdjList adjlist; //邻接表 int vex; //顶点数 int edge; //边数 }; void Init(AdjListGraph &G) { //初始化为未访问 for (int i = 0; i < MaxSize; i++) { visited[i] = false; } } int Location(AdjListGraph &G,char c) { //寻找顶点数据的邻接点 for (int i = 0; i < G.vex; i++) { if (G.adjlist[i].data == c) { return i; } } return -1; } void Create(AdjListGraph &G) { //创建图 cout << "请输入该图的顶点数以及边数:" << endl; cin >> G.vex >> G.edge; cout << "请输入相关顶点:" << endl; for (int i = 0; i < G.vex; i++) { cin >> G.adjlist[i].data; G.adjlist[i].fist = NULL; } char a, b; int m, n; cout << "请输入相关边的顶点:" << endl; for (int i = 0; i < G.edge; i++) { cin >> a >> b; m = Location(G, a); //寻找顶点号 n = Location(G, b); if (m != -1 && n != -1) { //寻找到位置 edgenode *temp = new edgenode; temp->adjvex = n; temp->next = G.adjlist[m].fist; G.adjlist[m].fist = temp; } } } void BFS(AdjListGraph &G,int v) { //图的广度遍历 queue <int> q; q.push(v); int temp; int w; while (!q.empty()) { //队列非空 temp = q.front(); //取对头元素 if (visited[temp] == false) { //如果没有被访问 cout << G.adjlist[temp].data << " "; visited[temp] = true; //设置为已访问 } q.pop(); //出队列 edgenode *tp = G.adjlist[temp].fist; if (tp != NULL) { w = tp->adjvex; q.push(w); //将第一个邻接点入队 while (tp->next != NULL) { //存在后续,同样入队列中 tp = tp->next; w = tp->adjvex; q.push(w); } } } } void BFS_Main(AdjListGraph &G) { //这个函数的存在是防止不连通图的存在 for (int i = 0; i < G.vex; i++) { if (visited[i] == false) { BFS(G,i); } } } int main() { AdjListGraph G; Init(G); Create(G); //创建图 BFS_Main(G); system("pause"); return 0; } /* 8 7 a b c d e f g h a b a f b c b d d e f g f h */
图的广度遍历(邻接表)
猜你喜欢
转载自blog.csdn.net/coolsunxu/article/details/80627937
今日推荐
周排行