#include<stdio.h>
#include<stdlib.h>
#include<queue>
#define INFINITY 65535
typedef int Status;
using namespace std;
#define MaxVerexNum 100
queue<int>q;
typedef struct
{
int Vex[MaxVerexNum];//顶点的数目
int Edge[MaxVerexNum][MaxVerexNum];//邻接矩阵
int vexnum,arcnum;//图当前的顶点数和弧数
}MGraph;//图的邻接矩阵定义
typedef struct QNode
{
int data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front,rear; //队头队尾指针
}LinkQueue;
//创建空队列
Status InitQueue(LinkQueue &Q)
{
Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));
if(!Q.front)
exit(0);
Q.front->next=NULL;
return 1;
}
//入队列
//将s作为新元素加入队尾
Status EnQueue(LinkQueue &Q,int i)
{
QueuePtr s;
s=(QueuePtr)malloc(sizeof(QNode));
if(!s)
exit(0);
s->data=i;
s->next=NULL;
Q.rear->next=s;
Q.rear=s;
return 1;
}
//检验是否为空
Status QueueEmpty(LinkQueue Q)
{
if(Q.front->next==NULL)
return 0;
else
return 1;
}
//出队列
Status DeQueue(LinkQueue *Q,int *i)
{
QueuePtr p;
if(Q->front==Q->rear)
return 0;
p=Q->front->next; //该写法值得商榷
//相当于p储存第一个结点
*i=p->data;
Q->front->next=p->next;
if(p==Q->rear) //若队头是队尾 ,删除后将rear指向头结点
Q->rear==Q->front;
free(p);
return 1;
}
void BFS(MGraph G)
{
int i,j;
LinkQueue Q;//初始化队列
int visited[G.vexnum];//访问标记数组
for(i=1;i<=G.vexnum;i++)
{
visited[i]=0;//初始化标记数组
}
InitQueue(Q);
for(i=1;i<=G.vexnum;i++)
{
if(visited[i]==0)
{
printf("%d\t",i);//访问当前节点
visited[i]=1;
EnQueue(Q,i);
while(!QueueEmpty(Q))
{
DeQueue(&Q,&i);
for(j=1;j<G.vexnum;j++)
{
if(G.Edge[i][j]==1&&visited[j]==0)
{
visited[j]=1;
printf("%d\t",j);
EnQueue(Q,j);
}
}
}
}
}
}
int main()
{
MGraph G;
int i,j;
G.vexnum=5;
G.arcnum=6;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
G.Edge[i][j]=0;
}
}
G.Edge[1][2]=G.Edge[2][1]=1;
G.Edge[1][4]=G.Edge[4][1]=1;
G.Edge[2][3]=G.Edge[3][2]=1;
G.Edge[2][5]=G.Edge[5][2]=1;
G.Edge[3][4]=G.Edge[4][3]=1;
G.Edge[3][5]=G.Edge[5][3]=1;
BFS(G);//进行广度优先遍历
return 0;
}
数据结构——图的广度优先遍历(邻接矩阵法)
最新推荐文章于 2022-10-21 10:20:13 发布