实现图的深度优先遍历和广度优先遍历(注意图的广度优先遍历需要辅助队列Q以及入队、出队函数。
#include<stdio.h>
#include<stdlib.h>
#define MAX 20
typedef int VexType;
typedef struct Vnode
{
VexType data;
struct Vnode * next;
}Vnode;
typedef Vnode Lgraph[MAX];
typedef struct{
int V[MAX];
int front;int rear;
}Queue;
/* 函数原型声明确规定*/
void creat_L(Lgraph G);
void output_L(Lgraph G);
void dfsL(Lgraph G,int v);
void bfsL(Lgraph G,int v);
Lgraph Ga;
int n,e,visited[MAX];
/*主函数*/
int main()
{
int v1,i;
for(i=0;i<MAX;i++) visited[i]=0;
creat_L(Ga);
output_L(Ga);
printf("please enter the start vex in depth first search:\n");
scanf("%d",&v1);
printf("the result of the depth first search:\n");
dfsL(Ga,v1);
for(i=0;i<MAX;i++) visited[i]=0;
printf("\nplease enter the start vex in breadth first search:\n");
scanf("%d",&v1);
printf("\nthe result of the breadth first search:\n");
bfsL(Ga,v1);
getchar();
}
/*建立无向图的邻接表*/
void creat_L(Lgraph G)
{
Vnode *p,*q;
int i,j,k;
printf("\nplease enter the number of the vex and edge\n");
scanf("%d,%d",&n,&e);
for(i=1;i<=n;i++){G[i].data=i;G[i].next=NULL;}
for(k=1;k<=e;k++)
{
printf("please enter each edge just like 1,2\n");
scanf("%d,%d",&i,&j);
p=(Vnode *)malloc(sizeof(Vnode));
p->data=i;
p->next=G[j].next;
G[j].next=p; /*p结点链接到第j条链*/
q=(Vnode *)malloc(sizeof(Vnode));
q->data=j;
q->next=G[i].next;
G[i].next=q; /*q结点链接到第i条链*/
}
}
/*邻接表的输出*/
void output_L(Lgraph G)
{
int i;
Vnode *p;
for(i=1;i<=n;i++)
{
printf("\n与 [%d] 相关的垂直点是:",i);
p=G[i].next;
while(p!=NULL){printf("%5d",p->data);p=p->next;/*p的下一个结点*/
}
}
}
/*初始化队列*/
void initqueue(Queue *q)
{
q->front=0;
q->rear=0;
}
/*判断队列是否为空*/
int quempty(Queue *q)
{
if(q->front == q->rear) /*如果队头等于队尾*/
return 1; /*则队列为空,返回1*/
else
return 0; /*否则队列不为空,返回0*/
}
/*入队操作*/
void enqueue(Queue *q,int e)
{
if((q->rear+1)%MAX == q->front) /*如果队列已满*/
printf("queue is full\n");
else
{
q->rear = (q->rear+1)%MAX; /*队尾指针加1取模*/
q->V[q->rear] = e; /*将元素放入队尾指针位置*/
}
}
/*出队操作*/
int dequeue(Queue *q)
{
int t;
if(q->front == q->rear)
{printf("queue is empty\n");return 0;}
else
{
t = q->V[q->front];
q->front = (q->front+1)%MAX;
return t;
}
}
/*深度优先遍历图*/
void dfsL(Lgraph G,int v)
{
Vnode *p;
printf("%d->",G[v].data);
visited[v]=1;
p=G[v].next;
while(p){v=p->data;if(visited[v]==0)dfsL(G,v);p=p->next;}
}
/*广度优先遍历图*/
void bfsL(Lgraph g,int v)
{
int x;
Vnode *p;
Queue *q=(Queue *)malloc(sizeof(Queue));
initqueue(q);
printf("\n%d->",g[v].data);
visited[v]=1;
enqueue(q,v);
while(!quempty(q))
{
x=dequeue(q);
p=g[x].next;
while(p){v=p->data;
if(visited[v]==0)
{
printf("%d->",g[v].data);
visited[v]=1;
enqueue(q,v);
}
p=p->next;
}
}
printf("\n");
}