无向图的广度优先遍历
#include <iostream>
#include
<stdio.h>
using namespace std;
#define MaxVertexNum 100
typedef
char VertexType;
typedef int EdgeType;
typedef int Datatype;
typedef
struct
{
VertexType vexs[MaxVertexNum];
EdgeType
edge[MaxVertexNum][MaxVertexNum];
int n,e;
}MGragh;
typedef struct
queuenode
{
Datatype data;
struct queuenode
*next;
}QueueNode;
typedef struct
{
QueueNode *
front;
QueueNode * rear;
}LinkQueue;
void InitQueue(LinkQueue *Q)
{
Q->front =
Q->rear = NULL;
}
int QueueEmpty(LinkQueue *Q)
{
return
Q->front == NULL && Q->rear == NULL;
}
void EnQueue(LinkQueue *Q,Datatype
x)
{
QueueNode *p = (QueueNode*)malloc(sizeof(QueueNode));
p->data
= x;
p->next = NULL;
if(QueueEmpty(Q))
Q->front = Q->rear
= p;
else
{
Q->rear->next = p;
Q->rear =
p;
}
}
Datatype DeQueue(LinkQueue *Q)
{
Datatype
x;
QueueNode *p;
if(QueueEmpty(Q))
printf("Queue Empty");
p =
Q->front;
x = p->data;
Q->front = p->next;
if(Q->rear
== p)
Q->rear = NULL;
free(p);
return x;
}
int visited[MaxVertexNum];
void DFS(MGragh *G,
int i);
MGragh* CreateMGraph(MGragh **G)
{
int i,j,k,w;
*G =
(MGragh*)malloc(sizeof(MGragh));
printf("请输入顶点数和边数:");
scanf("%d%d",&((*G)->n),
&((*G)->e));
fflush(stdin);
printf("请输入顶点值:(中间不要有空格如:ABCDEF)\n");
for(i
= 0; i< (*G)->n ;i++)
(*G)->vexs[i] = getchar();
for(i = 0; i
< (*G)->n; i++)
for(j = 0; j<(*G)->n;
j++)
(*G)->edge[i][j] =
0;
fflush(stdin);
printf("请输入(Vi,Vj)上的权w:\n");
for(k = 0; k <
(*G)->e;
k++)
{
scanf("%d%d%d",&i,&j,&w);
(*G)->edge[i][j]
= w;
(*G)->edge[j][i] = w;
}
return *G;
}
void DisMGraph(MGragh *G)
{
int
i,j;
for(i
=0;i<G->n;i++)
{
printf("\t");
for(j=0;j<G->n;j++)
printf("
%d\t",G->edge[i][j]);
printf("\n");
}
}
void DFSTraverse(MGragh *G,int
k)//深度优先遍历
{
int i;
for(i = 0; i<G->n;i++)
visited[i] =
0;
DFS(G,k);
for(i = 0; i<G->n;
i++)
{
if(!visited[i])
DFS(G,i);
}
}
void DFS(MGragh *G, int i)
{
cout <<
"visit vertex: "<<G->vexs[i]<<endl;
visited[i] =
1;
for(int j = 0;j<G->n;
j++)
{
if(G->edge[i][j]&&!visited[j])
DFS(G,j);
}
}
void BFS(MGragh *G, int k)
{
int
i,j,t;
LinkQueue Q;
InitQueue(&Q);
for(t = 0; t < G->n;
t++)
visited[t] = 0;
printf("visit vertex:
%c\n",G->vexs[k]);
visited[k] =
1;
EnQueue(&Q,k);
while(!QueueEmpty(&Q))
{
i =
DeQueue(&Q);
for(j = 0;
j<G->n;j++)
if(G->edge[i][j]&&!visited[j])
{
printf("visit
vertex: %c\n", G->vexs[j]);
visited[j] = 1;
EnQueue(&Q,
j);
}
}
}
void main()
{
MGragh *G =
NULL,*P=NULL;
int i;
P =
CreateMGraph(&G);
DisMGraph(P);
printf("请输入要遍历的顶点编号:");
scanf("%d",&i);
printf("深度优先遍历顺序是:\n");
DFSTraverse(P,i);
printf("广度优先遍历顺序是:\n");
BFS(P,i);
}