当前位置:
文档之家› 采用邻接表存储结构实现图的广度优先遍历
采用邻接表存储结构实现图的广度优先遍历
p=[w].firstarc;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
{
printf("%3d",p->adjvex+1);
visited[p->adjvex]=1;
rear=(rear+1)%MAX_NUM;
queue[rear]=p->adjvex;}
p=p->nextarc;}
typedef int VertexType;
typedef enum {DG=1,UDG}GraphKind;
typedef struct ArcNode
{
int adjvex;
int weight;
struct ArcNode *nextarc;
ArcNode *info;
}ArcNode;
typedef struct VNode
scanf("%d",&[i].data);
[i].firstarc=NULL;}
for(i=0;i<;++i)
{
printf("第%d条边的起始顶点编号和终止顶点编号:",i+1);
scanf("%d %d",&s,&d);
while(s<1||s>||d<1||d>
{
printf("编号超出范围,重新输入");
scanf("%d%d",&s,&d);}
s--;
d--;
p=new(ArcNode);
p->adjvex=d;
p->nextarc=[s].firstarc;
[s].firstarc=p;
}
}
void Creat_adjgraphUDG(ALGraph &G)
{
int i,s,d;
ArcNode *p,*q;
课程设计题目九:图的广度优先遍历
基本要求:
采用邻接表存储结构实现图的广度优先遍历。
(2)对任意给定的图(顶点数和边数自定),建立它的邻接表并输出;
(3)实现图的广度优先遍历*/
#include<>
#include<>
#include<>
#define MAX_NUM 20
int visited[MAX_NUM]={0};
case UDG:Creat_adjgraphUDG(G);PRIN(G);break;
default:printf("ERROR");break;
}
}
void main()
{
ALGraph G;Creat_adjgraph(G);printf("\n");
printf("广度优先搜索遍历序列为:\n");
scanf("%d %d",&s,&d);
while(s<1||s>||d<1||d>
{
printf("编号超出范围,重新输入");
scanf("%d %d",&s,&d);}
s--;
d--;
p=new(ArcNode);
p->adjvex=d;
p->nextarc=[s].firstarc;
[s].firstarc=p;
int w,i;
for(i=0;i<;i++)visited[i]=0;
printf("%4d",v+1);
visited[v]=1;
rear=(rear+1)%MAX_NUM;
queue[rear]=v;
while(front!=rear)
{
front=(front+1)%MAX_NUM;
w=queue[front];
void Creat_adjgraphDG(ALGraph &G)
{
int i,s,d;
ArcNode *p=NULL,*q=NULL;=DG;
printf("请输入顶点数和边数:");
scanf("%d %d",&,&;
for(i=0;i<;++i)
{
printf("第%d个顶点信息:",i+1);
bfs(G,1);printf("\n");
}
p=[i].firstarc;
while(p!=NULL)
{
printf("%d\t",p->adjvex+1);
p=p->nextarc;}
printf("\n");}
}
}
void bfs(ALGraph &G,int v)
{
v--;
ArcNode *p;
int queue[MAX_NUM],front=0,rear=0;
=UDG;
printf("请输入顶点数和边数:");
scanf("%d %d",&,&;
for(i=0;i<;++i)
{
printf("第%d个顶点信息:",i+1);
scanf("%d",&[i].data);
[i].firstarc=NULL;}
for(i=0;i<;++i)
{
printf("第%d条边的起始顶点编号和终止顶点编号:",i+1);
{
VertexType data;
ArcNode *firstarc;
}VNode,AdjList[MAX_NUM];
typedef struct
{
AdjList vertices;
int vexnum,arcnum;
GraphKind kind;
}ALGraph;
void PRIN(ALGraph &G);
q=new(ArcNode);
q-=[d].firstarc;
[d].firstarc=q;
}
}
void PRIN(ALGraph &G)
{
int i;
ArcNode *p;
if==DG||==UDG)
{
for(i=0;i<;++i)
{
printf("V%d:",[i].data);
void Creat_adjgraph(ALGraph &G);
void bfs(ALGraph &G,int v);
void Creat_adjgraphDG(ALGraph &G);
void Creat_adjgraphUDG(ALGraph &G);
void Creat_adjgraph(ALGraph &G);
}
printf("\n");
}
void Creat_adjgraph(ALGraph &G)
{
printf("1:有向图2:无向图\n");
printf("请根据上述提示输入图的类型:"
);
scanf("%d",&;
switch
{
case DG:Creat_adjgraphDG(G);PRIN(G);break;