2019年06月17日
阅读 573
评论 0
喜欢 0
- MGraph是Matrix Graph邻接矩阵; AGraph是Adjacent Graph邻接表
- 两种存储结构都是由邻接矩阵初始化的
- 边表的初始化是用头插法,理解头插法的最佳想象是在有很多结点的情况下继续插,用从零开始的想法去做有点困
难。 - 什么是广度优先遍历?就是:while(队列非空){出队;入队;}
声明一个队列→挑一个元素入队→while(队列非空)→出队→以出队者为基准摸查其相邻结点,若结点未访问,入队
邻接矩阵存储结构
#define MAXV 10
typedef char ElemType;
struct VertexType {
int no;
ElemType info;
};
struct MGraph {
int n,e;
int edges[MAXV][MAXV];
VertexType vexs[MAXV];
};
生成图的邻接矩阵算法
void CreateMat(MGraph &g,int A[][MAXV],int n) {
int i,j;
g.n=n;
g.e=0;
for(i=0; i<n; i++)
for(j=0; j<n; j++) {
g.edges[i][j]=A[i][j];
if(g.edges[i][j]!=0)
g.e++;
}
}
输出图的邻接矩阵算法
void DispMat(MGraph g) {
int i,j;
for(i=0; i<g.n; i++) {
for(j=0; j<g.n; j++)
printf("%4d",g.edges[i][j]);
printf("\n");
}
}
邻接表存储结构
typedef char ElemType;
typedef int InfoType;
struct ArcNode {
int adjvex;
struct ArcNode *nextarc;
InfoType info;
};
struct VNode {
ElemType data;
ArcNode *firstarc;
};
typedef VNode AdjList[MAXV];
struct AGraph {
AdjList adjlist;
int n,e;
};
生成图的邻接表算法
void CreateAdj(AGraph *&G,int A[][MAXV],int n) {
int i,j;
ArcNode *p;
G=(AGraph *)malloc(sizeof(AGraph));
G->n=n;
G->e=0;
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) {
p=(ArcNode *)malloc(sizeof(ArcNode));
p->adjvex=j;
p->nextarc=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
G->e++;
}
}
输出图的邻接表算法
void DispAdj(AGraph *G) {
int i;
ArcNode *p;
for(i=0; i<G->n; i++) {
cout<<i<<"->";
p=G->adjlist[i].firstarc;
while(p!=NULL) {
cout<<p->adjvex<<"->";
p=p->nextarc;
}
cout<<"^"<<endl;
}
}
暂无评论