数据结构——图
小白专场
常用的存图方式有两种:
一.用邻接矩阵来存图,顾名思义就是用一个矩阵来存图。
二.用邻接表表示图。
此文章我们来介绍第一种表示方法:
用邻接矩阵来存图,很自然的我们会想到用一个二维数组去表示图
1.所以我们创建一个图结点,包含:一个二维数组,边数,顶点数,和顶点的数据类型。
2.然后还需要一个结点表示插入边的信息包含了:V1,V2两个结点,和边的权重值。
3.有结点之后我们就需要建立一个空表,需要自己定义一个函数来实现。
4.有了空表之后我们就需要把边插入空表,者须再定义一个函数来实现插边。
5.之后我们就可以建立一张完整的图表啦!
说了这么多让我们来看看代码实现吧!
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
typedef int Vertex;
typedef int WeightType;
typedef int DataType;
typedef int weightType;
#define MaxvertexNum 100
//................................................此行 为黄金分割线
typedef struct GNode*PtrToGNode;
struct GNode{//图结点
int Nv;//顶点数
int Ne;//边数
WeightType G[MaxvertexNum][MaxvertexNum];
DataType Data[MaxvertexNum];//此数组用来存顶点的数据类型
};
typedef PtrToGNode MGraph;//以邻接矩阵存储的图类型
//................................................
typedef struct ENode *PtrToENode;
struct ENode{//边结点
Vertex V1,V2;//有向边<V1,V2>
weightType Weight;//权重
};
typedef PtrToENode Edge;
//................................................
MGraph CreateGraph(int VertexNum);//MGraph初始化
//................................................
MGraph BuildGraph();//完整地建立一个MGraph
//................................................
void InsertEdge(MGraph Graph,Edge E);//向MGraph中插入边
//................................................
int main(){
MGraph GM;
GM=BuildGraph();
for(int i=0;i<GM->Nv;i++){
for(int j=0;j<GM->Nv;j++){
printf("%d ",GM->G[i][j]);
}
printf("\n");
}
return 0;
}
MGraph CreateGraph(int VertexNum){//MGraph初始化
Vertex V,W;//顶点
MGraph Graph;
Graph=(MGraph)malloc(sizeof(struct GNode));
Graph->Nv=VertexNum;
Graph->Ne=0;
for(V=0;V<VertexNum;V++){
for(W=0;W<VertexNum;W++){
Graph->G[V][W]=0;
}
}
return Graph;
}
MGraph BuildGraph(){//完整地建立一个MGraph
MGraph Graph;
int Nv;
Edge E;
Vertex V;
scanf("%d",&Nv);
Graph=CreateGraph(Nv);
scanf("%d",&Graph->Ne);
if(Graph->Ne!=0){
E=(Edge)malloc(sizeof(struct ENode));
for(int i=0;i<Graph->Ne;i++){
scanf("%d %d %d",&E->V1,&E->V2,&E->Weight);
InsertEdge(Graph,E);
}
}
for(V=0;V<Graph->Nv;V++){//如果顶点有数据的话,读入数据类型
scanf("%d",&Graph->Data[V]);
}
return Graph;
}
void InsertEdge(MGraph Graph,Edge E){//向MGraph中插入边
//插入边<V1,V2>
Graph->G[E->V1][E->V2]=E->Weight;
//如果是无向图
Graph->G[E->V2][E->V1]=E->Weight;
}
此代码基于C语言编写!