#include<iostream>
#define MAXSIZE 100
using namespace std;
typedef struct ArcNode
{
int adjvex;
struct ArcNode *next;
int info;
}ArcNode;
typedef struct VNode
{
char data;
ArcNode *firsstarc;
}VNode,AdjList[MAXSIZE];
typedef struct
{
AdjList vertices;
int vexnum,arcnum;
}ALGraph;
typedef struct Queue
{
int *base;
int rear;
int front;
}Queue;
void initQueue(Queue &Q)
{
Q.base=new int[MAXSIZE];
Q.front=0;
Q.rear=0;
return;
}
bool EnQueue(Queue &Q,int e)
{
if((Q.rear+1)%MAXSIZE==Q.front)
return false;
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXSIZE;
return true;
}
bool DeQueue(Queue &Q,int &e)
{
if(Q.rear==Q.front)
return false;
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXSIZE;
return true;
}
int LocateVex(ALGraph G,char v)
{
for(int i=0;i<G.vexnum;i++)
{
if(G.vertices[i].data==v)
return i;
}
}
bool CreatUDG(ALGraph &G)
{
cout<<"输入顶点的个数和边个数:";
cin>>G.vexnum>>G.arcnum;
for(int i=0;i<G.vexnum;i++)
{
cout<<"第"<<i+1<<"个点为:";
cin>>G.vertices[i].data;
G.vertices[i].firsstarc=NULL;
}
for(int k=0;k<G.arcnum;k++)
{
char v1,v2;
cout<<"输入两个相关的点:";
cin>>v1>>v2;
int i=LocateVex(G,v1);
int j=LocateVex(G,v2);
ArcNode *p1;
p1=new ArcNode;
p1->adjvex=j;
p1->next=G.vertices[i].firsstarc;
G.vertices[i].firsstarc=p1;
ArcNode *p2;
p2=new ArcNode;
p2->adjvex=i;
p2->next=G.vertices[j].firsstarc;
G.vertices[j].firsstarc=p2;
}
return true;
}
bool visited[MAXSIZE];
void BFS(ALGraph G,int v)
{
cout<<G.vertices[v].data<<" ";
visited[v]=true;
Queue Q;
initQueue(Q);
EnQueue(Q,v);
int e;
while(Q.front!=Q.rear)
{
DeQueue(Q,e);
ArcNode *p;
p=G.vertices[e].firsstarc;
for(p;p;p=p->next)
{
int w=p->adjvex;
if(!visited[w])
{
cout<<G.vertices[w].data<<" ";
visited[w]=true;
EnQueue(Q,w);
}
}
}
return ;
}
int main()
{
ALGraph G;
CreatUDG(G);
int i;
cout<<"进行遍历的出发的顶点为:";
cin>>i;
cout<<"显示如下:"<<endl;
BFS(G,i);
return 0;
}
本代码以广度优先进行遍历,应用到广度(BFS)的相关操作算法,本代码用C++进行编译,深度优先则在同一笔记数据结构-----图的深度优先中可查看。