作业:用邻接表实现图的深度与广度优先遍历。(做出来的遍历结果序列有问题)
程序如下:
/*邻接表表示的图的深度优先搜索和广度优先搜索程序*/
#include <stdio.h>
#define maxvertexnum 100
#define queuesize 100
#define null 0
typedef struct
{
int front,rear,count,data[queuesize];
}cirqueue;
typedef int vertextype;
/*图的邻接表的边结点定义*/
typedef struct node
{
int adjvex;
struct node *next;
}edgenode;
/*图的邻接表表示的顶点结点定义*/
typedef struct vnode
{
vertextype vertex;
edgenode *firstedge;
}vertexnode;
typedef vertexnode adjlist[maxvertexnum];
/*定义图的邻接表*/
typedef struct
{
adjlist adjlist;
int n;
int e;
}algraph;
typedef enum
{
FALSE,TRUE
}boolean;
boolean visited[maxvertexnum];
/*建立图g的邻接表表示*/
void createalgraph(algraph *g)
{
int i,j,k;
int flag;
edgenode *s;
printf("\ncreat:\n");
printf("digraph--0\n");
printf("undigraph--1\n");
scanf("%d",&flag);
printf("input n,e\n");
scanf("%d,%d",&g->n,&g->e);
printf("input nodes:\n");
for(i=0;i<g->n;i++)
{
scanf("%d",&(g->adjlist.vertex));
g->adjlist.firstedge=null;
}
for(k=0;k<g->e;k++)
{
printf("input i,j(0~n-1):\n");
scanf("%d,%d",&i,&j);
s=(edgenode *)malloc(sizeof(edgenode));
s->adjvex=j;
s->next=g->adjlist.firstedge;
g->adjlist.firstedge=s;
if (flag)
{
s=(edgenode *)malloc(sizeof(edgenode));
s->adjvex=i;
s->next=g->adjlist[j].firstedge;
g->adjlist[j].firstedge=s;
}
}
}
void dfs(algraph *g,int i)
{
edgenode *p;
printf("\nvisit vertex:%d",g->adjlist.vertex);
visited=TRUE;
p=g->adjlist.firstedge;
while(p)
{
if (!visited[p->adjvex])
dfs(g,p->adjvex);
p=p->next;
}
}
/*对以邻接表表示的图g进行深度优先搜索*/
void dfstraverse(algraph *g)
{
int i;
for(i=0;i<g->n;i++)
visited=FALSE;
for(i=0;i<g->n;i++)
if(!visited)
dfs(g,i);
printf("\n");
}
void bfs(algraph *g,int k)
{
int i,j;
cirqueue *q;
edgenode *p;
q=(cirqueue *)malloc(sizeof(cirqueue));
q->rear=q->front=q->count=0;
printf("\nvisit vertex:%d",g->adjlist[k].vertex);
visited[k]=TRUE;
q->data[q->r