#include <iostream>
#include <stdio.h>//注意
#include <stdlib.h>//注意
#include <string.h>
using namespace std;
#define MAX_VERTEX_NUM 20
#define MAX_VEX 20
typedef string VertexType,VexType;
typedef int ElemType;
typedef int EdgeType,InfoType;
int Visited[MAX_VEX] ;
typedef struct ArcNode{ //边(弧)结点的类型定义
int adjvex; //边(弧)的另一顶点的在数组中的位置
ArcNode *nextarc;//指向下一边(弧)结点的指针
InfoType *info; //该弧相关信息的指针
}ArcNode;
typedef struct Vnode{//顶点结点及其数组的类型定义
VertexType data; //顶点信息
ArcNode * firstarc; //指向关联该顶点的边(弧)链表
} Vnode, AdjList[MAX_VERTEX_NUM];
typedef struct {
AdjList vertices;
int vexnum, arcnum; //图的当前顶点数和弧数
int kind; //图的种类标志
} ALGraph; //图邻接表类型
typedef struct
{
ElemType elem[MAX_VEX];
int front;
int rear;
}sqQueue;
void InitQueue(sqQueue &q)
{
q.front=q.rear=0;
}
void EnQueue(sqQueue &q,int v)
{
q.elem[q.rear]=v;
q.rear++;
}
void DeQueue(sqQueue &q,int &v)
{
v=q.elem[q.front];
q.front++;
}
int QueueEmpty(sqQueue q)
{
if(q.front==q.rear)
return 1;
else
return 0;
}
int LocateVex(ALGraph &G , VexType vp)
{
int k=0 ;
for (k=0 ; k<G.vexnum ; k++)
{if (G. vertices[k].data==vp) return(k) ;}
return(-1) ; /* 图中无此顶点 */
}
void CreatALGraph(ALGraph &G)//无向图的创建
{
string e1,e2;
int k,l=0,m=0;
ArcNode *s1,*s2;
cin>>G.vexnum>>G.arcnum; //输入顶点数和边数
for( int i=0;i<G.vexnum;i++)
{ cin>>G.vertices[i].data;//输入顶点信息
G.vertices[i].firstarc=NULL;
}
for(k=0;k<G.arcnum;k++)
{ cin>>e1>>e2;
l=LocateVex(G,e1);
m=LocateVex(G,e2);
s1=(ArcNode*)malloc(sizeof(ArcNode));
s1->adjvex=m;
s1->nextarc=G.vertices[l].firstarc;
G.vertices[l].firstarc=s1;
s2=(ArcNode*)malloc(sizeof(ArcNode));
s2->adjvex=l;
s2->nextarc=G.vertices[m].firstarc;
G.vertices[m].firstarc=s2;
}
}
void OutputALGraph(ALGraph &G)//邻接表的输出
{ int i;
for(i=0;i<G.vexnum;i++)
{ ArcNode *s;
cout<<i<<" "<<G.vertices[i].data<<endl; //顶点信息
s=G.vertices[i].firstarc;
while(s!=NULL)
{ printf(" %d",s->adjvex);
s=s->nextarc; }
printf("\n");
}
}
int FirstAdjvex(ALGraph G,int u)
{
ArcNode *t;
t=G.vertices[u].firstarc;
if(t!=NULL)
return t->adjvex;
else
return -1;
}
int NextAdjvex(ALGraph G,int u,int w)
{
ArcNode *t;
t=G.vertices[u].firstarc;
while(t!=NULL)
{
if(t->adjvex!=w)
t=t->nextarc;
else if(t->nextarc!=NULL)
return t->nextarc->adjvex;
else
return -1;
}
return -1;
}
void BFS(ALGraph G,int v)
{ sqQueue q;
int u,w;
cout<<G.vertices[v].data<<" ";
Visited[v]=true;
InitQueue(q);
EnQueue(q,v);
while(!QueueEmpty(q))
{
DeQueue(q,u);
for(w=FirstAdjvex(G,u);w>=0;w=NextAdjvex(G,u,w))
if(!Visited[w])
{
cout<<G.vertices[w].data<<" ";
Visited[w]=true;
EnQueue(q,w);
}
}
}
void BFStraverse(ALGraph G)
{ int i;
for(i=0;i<G.vexnum;i++)
Visited[i]=false;
for(i=0;i<G.vexnum;i++)
{
if(!Visited[i])
BFS(G,i);
}
}
int main()
{
ALGraph G;
CreatALGraph(G);
//OutputALGraph(G);
BFStraverse(G);
return 0;
}
无向图的广度遍历非递归
最新推荐文章于 2023-03-07 20:39:54 发布