33,311
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <malloc.h>
#define MaxSize 50
#define MAXV 5
#define INF 32767
typedef int ElemType;
typedef int InfoType;
typedef struct
{
int no;
InfoType info;
}VertexType;
typedef struct
{
int edges[MAXV][MAXV];
int n,e;
VertexType vexs[MAXV];
}MatGraph;
typedef struct
{
ElemType data[MaxSize];
int front,rear;
}SqQueue;
typedef struct ANode
{
int adjvex;
struct ANode *nextarc;
int weight;
}ArcNode;
typedef struct VNode
{
InfoType info;
ArcNode *firstarc;
}VNode;
typedef struct
{
VNode adjlist[MAXV];
int n,e;
}AdjGraph;
void InitQueue(SqQueue *&q)
{
q=(SqQueue *)malloc(sizeof(SqQueue));
q->front=q->rear=0;
}
bool QueueEmpty(SqQueue *q)
{
return(q->front==q->rear);
}
bool enQueue(SqQueue *&q,ElemType e)
{
if((q->rear+1)%MaxSize==q->front)
return false;
q->rear=(q->rear+1)%MaxSize;
q->data[q->rear]=e;
return true;
}
bool deQueue(SqQueue *&q,ElemType &e)
{
if(q->front==q->rear)
return false;
q->front=(q->front+1)%MaxSize;
e=q->data[q->front];
return true;
}
void CreateAdj(AdjGraph *&G,int A[MAXV][MAXV],int n,int e)
{
int i,j;ArcNode *p;
G=(AdjGraph *)malloc(sizeof(AdjGraph));
for(i=0;i<n;i++)
G->adjlist[i].firstarc=NULL;
for(i=0;i<n;i++)
for(j=n-1;j>=0;j--)
if(A[i][j]!=0&&A[i][j]!=INF)
{
p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=j;
p->weight=A[i][j];
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
G->n=n;G->e=n;
}
void DestroyAdj(AdjGraph *&G)
{
int i;
ArcNode *pre,*p;
for(i=0;i<G->n;i++)
{
pre=G->adjlist[i].firstarc;
if(pre!=NULL)
{
p=pre->nextarc;
while(p!=NULL)
{
free(pre);
pre=p;p=p->nextarc;
}
free(pre);
}
}
free(G);
}
int visited[MAXV]={0};
void DFS(AdjGraph *G,int v)
{
ArcNode *p;
visited[v]=1;
printf("%d ",v);
p=G->adjlist[v].firstarc;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
DFS(G,p->adjvex);
p=p->nextarc;
}
}
void BFS(AdjGraph *G,int v)
{
int w,i;ArcNode *p;
SqQueue *qu;
InitQueue(qu);
int visited[MAXV];
for(i=0;i<G->n;i++)
visited[i]=0;
printf("%2d",v);
visited[v]=1;
enQueue(qu,v);
while(!QueueEmpty(qu))
{
deQueue(qu,w);
p=G->adjlist[w].firstarc;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
{
printf("%2d",p->adjvex);
visited[p->adjvex]=1;
enQueue(qu,p->adjvex);
}
p=p->nextarc;
}
}
printf("\n");
}
int main()
{
int i,j;
MatGraph g;
AdjGraph *G;
int A[MAXV][MAXV];
printf("请输入邻接矩阵:\n");
for(i=0;i<6;i++)
for(j=0;j<6;j++)
scanf("%d ",&A[i][j]);
CreateAdj(G,A[5][5],6,10);
printf("从顶点0开始的深度优先遍历结果为:\n");
DFS(G,0);
printf("从顶点0开始的广度优先遍历结果为:\n");
BFS(G,0);
DestroyAdj(G);
return 0;
}