您的位置:首页 > 其它

图的广度优先遍历(邻接表存储)

2012-09-21 15:30 706 查看
图的广度优先搜索类似于树的按层遍历,遍历过程中要用到队列(因为队列中的元素为先进先出),BFS的思想很简单,以下给出完整的代码

#include <iostream>
typedef char InfoType;
typedef char VertexType;
typedef char QElemType;
#define ERROR -1;
#define OK 1;
bool visited[20];
using namespace std;
typedef struct Qnode{
QElemType data;
struct Qnode *next;
}Qnode,*QueuePtr;

typedef struct{
QueuePtr front;   //队头指针
QueuePtr rear;    //队尾指针
}LinkQueue;

typedef struct ArcNode{
int adjvex;       //该弧所依附的结点的位置编号
struct ArcNode *nextarc;  //指向下一条弧的指针
InfoType *info;           //指向存储弧的信息的指针
}ArcNode;

typedef struct VNode{
ArcNode *firstarc;   //依附于该结点的第一条弧
VertexType data;     //节点信息
}Vnode,AdjList[20];

typedef struct{
int vexnum,arcnum;   //图的结点个数和弧的个数
AdjList vertices;    //存放图的结点的位置向量
}ALGraph;

void InitQueue(LinkQueue &Q){
Q.rear=Q.front=(QueuePtr)malloc(sizeof(Qnode));
if(!Q.front)
exit(0);
Q.front->next=NULL;
}

int QueueEmpty(LinkQueue &Q){
return((Q.front==Q.rear)?1:0);
}

void EnQueue(LinkQueue &Q,QElemType e){
QueuePtr p;
p=(QueuePtr)malloc(sizeof(Qnode));
if(!p)
exit(0);
p->data=e;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
}

int DeQueue(LinkQueue &Q,QElemType &e){
QueuePtr p;
if(Q.front==Q.rear)
return ERROR;
p=Q.front->next;
e=p->data;
Q.front->next=p->next;
if(Q.rear==p)
Q.rear=Q.front;
free(p);
return OK;
}

int LocateVex(ALGraph G,VertexType v){  //确定某一个节点在图中的位置编号
for(int i=0;i<G.vexnum;i++){
if(G.vertices[i].data==v)
return i;
}
return ERROR;
}

void CreateUDG(ALGraph &G){  //创建图,用邻接表存储
VertexType v1,v2;
ArcNode *p,*q;
int i,j,k;
cout<<"请输入图中结点的个数和弧的个数:";
cin>>G.vexnum;
cin>>G.arcnum;
cout<<"请输入图中各个结点的值:";
for(i=0;i<G.vexnum;i++){
cin>>G.vertices[i].data;
G.vertices[i].firstarc=NULL;
}
for(k=0;k<G.arcnum;k++){
cout<<"请输入图中连接弧的两个结点的值:";
cin>>v1;
cin>>v2;
i=LocateVex(G,v1);
j=LocateVex(G,v2);
p=(ArcNode *)malloc(sizeof(ArcNode));
q=(ArcNode *)malloc(sizeof(ArcNode));
p->nextarc=G.vertices[i].firstarc;
q->nextarc=G.vertices[j].firstarc;
G.vertices[i].firstarc=p;
p->adjvex=j;
G.vertices[j].firstarc=q;
q->adjvex=i;
}
}

void BFSTraverse(ALGraph G){
int i,j,n;
ArcNode *w;
LinkQueue Q;
VertexType u;
for(i=0;i<G.vexnum;i++)
visited[i]=false;
InitQueue(Q);
for(i=0;i<G.vexnum;i++){
if(!visited[i]){
visited[i]=true;
EnQueue(Q,G.vertices[i].data);
}
while(!QueueEmpty(Q)){
DeQueue(Q,u);
cout<<u<<"  ";
for(j=0;j<G.vexnum;j++){
if(G.vertices[j].data==u){
n=j;
break;
}
}
for(w=G.vertices
.firstarc;w;w=w->nextarc){
if(!visited[w->adjvex]){
visited[w->adjvex]=true;
EnQueue(Q,G.vertices[w->adjvex].data);
}
}
}
}
}

void main(){
ALGraph G;
CreateUDG(G);
cout<<"广度优先遍历的结果是:"<<endl;
BFSTraverse(G);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: