当前位置:文档之家› 实验报告:图的存储结构和遍历

实验报告:图的存储结构和遍历

武汉东湖学院
实验报告
学院:计算机科学学院—专业计算机科学与技术2016年11月18日
1.实验目的
(1)了解邻接矩阵存储法和邻接表存储法的实现过程。

(2)了解图的深度优先遍历和广度优先遍历的实现过程。

2.实验内容
1.采用图的邻接矩阵存储方法,实现下图的邻接矩阵存储,并输出该矩阵
2.设计一个将第1小题中的邻接矩阵转换为邻接表的算法,并设计一个在屏幕上显示邻接表的算法
3.实现基于第2小题中邻接表的深度优先遍历算法,并输出遍历序列
4.实现基于第2小题中邻接表的广度优先遍历算法,并输出遍历序列
3.实验环境Visual C++ 6.0
4 .实验方法和步骤(含设计)
我们通过二维数组中的值来表示图中节点与节点的关系。

通过上图可 知,
其邻接矩阵示意图为如下: V0
v1 v2 v3 v4 v5 V0
1 0
1 0
1
V1 1 0 1 1 1 0 V2 0 1 0 0 1 0 V3 1 1 0 0 1 1 V4 0 1 1 1 0 0 V5 1
1
此时的 “1 ” 表示这两个节点有关系,“ 0”表示这两个节点无关系
我们通过邻接表来在计算机中存储图时,其邻接表存储图如下:
5.程序及测试结果
#include <stdio.h>
#include <malloc.h>
int visited [6];
typedef struct
{ int a[6][6];
int n;
}mgraph;
typedef struct ANode
{
int adjvex;
struct ANode *nextarc;
}ArcNode;
typedef struct Vnode
{
ArcNode *firstarc;
}VNode;
typedef VNode AdjList [6];
typedef struct
{ AdjList adjlist;
int n;
}ALGraph;
void mattolist (mgraph g,ALGraph *&G)
{ int i,j;
ArcNode *p; G=(ALGraph*)malloc(sizeof(ALGraph));
for(i=0;i<g.n;i++)
G->adjlist[i].firstarc=NULL;
for(i=0;i<g.n;i++)
for(j=g.n-1;j>=0;j--)
if(g.a[i][j]!=0)
{ p=(ArcNode*)malloc(sizeof(ArcNode)); p->adjvex=j;
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
G->n=g.n;
}
void dispadj(ALGraph *G)
{ int i;
ArcNode *p;
for(i=0;i<G->n;i++)
{ p=G->adjlist[i].firstarc; printf("%d:",i);
while (p!=NULL)
{ printf("%d ",p->adjvex); p=p_>nextarc;
}
printf("\n");
}
}
void dfs (ALGraph *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 (ALGraph *G ,int v)
{ ArcNode *p;
int queue[6],front=0,rear=0;
int visited[6];
int w,i;
for(i=0;i<G->n;i++)
visited[i]=0;
printf("%d ",v);
visited[v]=1;
rear=(rea 叶1)%6;
queue[rear]=v;
while (front!=rear)
{ front=(front+1)%6; w=queue[front];
p=G->adjlist[w].firstarc; while(p!=NULL)
{
if(visited[p->adjvex]==0)
{
printf("%d ",p->adjvex); visited[p->adjvex]=1;
rear=(rea 叶1)%6;
queue[rear]=p->adjvex;
}
p=p_>nextarc;
}
}
printf("\n");
int main ()
{
mgraph g;
ALGraph *G;
int a[6][6]={{0,1,0,1,0,1},{1,0,1,1,1,0},{0,1,0,0,1,0},
{1,1,0,0,1,1},{0,1,1,1,0,0},{1,0,0,1,0,0}};
int i,j;
g.n=6;
for(i=0;i<g.n;i++)
for(j=0;jvg.n;j++)
g.a[i][j]=a[i][j];
for(i=0;i<g.n;i++)
{ for(j=0;j<g.n;j++)
printf("%d ",g.a[i][j]);
printf("\n");
}
printf(" -------- 邻接矩阵---------- \n");
G=(ALGraph*)malloc(sizeof(ALGraph));
mattolist(g,G);
dispadj(G);
printf(" -------- 令B接表---------- \n");
dfs(G,0);
printf("\n");
printf(" -------- 从0开始的深度优先遍历--------------- \n");
bfs(G,0);
printf("\n");
printf(" -------- 从0开始的广度优先遍历--------------- \n");
return 0;
实验日期:2016年11月17 日。

相关主题