#include<iostream>
using namespace std;
#define QSIZE 20
#define MAXVEX 30
typedef char VType;
typedef int EType;
typedef struct ENode
{
int Avex;
struct ENode *pNext;
}ENode, *pENode;
typedef struct VNode
{
VType data;
ENode *pFirst;
}VNode, VNodeL[MAXVEX];
typedef struct
{
VNodeL VLnode;
int Vnums;
int Enums;
}ALGraph;
typedef struct Queue
{
int *pBase;
int Front;
int Rear;
}Queue;
void InitQueue(Queue &Q)
{
Q.pBase = new int[QSIZE];
Q.Front = 0;
Q.Rear = 0;
}
bool QueueFull(Queue &Q)
{
if ((Q.Rear + 1) % QSIZE == Q.Front)
return true;
else
return false;
}
bool QueueEmpty(Queue &Q)
{
if (Q.Front == Q.Rear)
return true;
else
return false;
}
bool EnQueue(Queue &Q, int pos)
{
if (QueueFull(Q))
return false;
Q.pBase[Q.Rear] = pos;
Q.Rear = (Q.Rear + 1) % QSIZE;
}
bool DeQueue(Queue &Q,int &pos)
{
if (QueueEmpty(Q))
return false;
pos = Q.pBase[Q.Front];
Q.Front = (Q.Front + 1) % QSIZE;
}
void CreateALGraph(ALGraph &G)
{
int i, j, k;
ENode *pE;
cin >> G.Vnums >> G.Enums;
for (i = 0; i < G.Vnums; ++i)
{
cin >> G.VLnode[i].data;
G.VLnode[i].pFirst = NULL;
}
for (k = 0; k < G.Enums; ++k)
{
cin >> i >> j;
pE = new ENode;
pE->Avex = i;
pE->pNext = G.VLnode[j].pFirst;
G.VLnode[j].pFirst = pE;
pE = new ENode;
pE->Avex = j;
pE->pNext = G.VLnode[i].pFirst;
G.VLnode[i].pFirst = pE;
}
}
bool VTag[MAXVEX];
void Visit(VType v)
{
cout << v << " ";
}
void BFSPrint(ALGraph G)
{
int i, j;
pENode pE;
Queue Q;
InitQueue(Q);
for (i = 0; i < G.Vnums; ++i)
VTag[i] = false;
for (i = 0; i < G.Vnums; ++i)
{
if (!VTag[i])
{
VTag[i] = true;
Visit(G.VLnode[i].data);
EnQueue(Q,i);
while (!QueueEmpty(Q))
{
DeQueue(Q,i);
pE = G.VLnode[i].pFirst;
while (pE)//是否有相邻边表结点
{
if (!VTag[pE->Avex])//是否被访问过
{
VTag[pE->Avex] = true;
Visit(G.VLnode[pE->Avex].data);
EnQueue(Q, pE->Avex);
}
pE = pE->pNext;
}
}
}
}
}
int main(void)
{
ALGraph G;
CreateALGraph(G);
BFSPrint(G);
return(0);
}
图的邻接表BFS(参考C博客—研究毛)
最新推荐文章于 2022-05-18 21:24:33 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)