图的储存之邻接矩阵

来源:互联网 发布:新开淘宝店卖什么好 编辑:程序博客网 时间:2024/05/29 07:38
#include<iostream>#include<cstring>#include<cstdlib>using namespace std;#define MaxVertexNum 100   //最大顶点数设为100 #define INFINTY 65535      typedef int Vertex;        //用顶点下标表示顶点,为整形typedef int WeightType;    //边的权值设为整数typedef char DataType;     //顶点储存数据类型为字符型//图节点的定义typedef struct GNode *PtrToGNode;struct GNode{int Nv;//顶点数int Ne;//边数WeightType G[MaxVertexNum][MaxVertexNum];//邻阶矩阵DataType Data[MaxVertexNum];//存顶点数据//注意:若顶点无数据,此时Data[]可以不出现 };typedef PtrToGNode MGraph;//以邻阶矩阵 储存的图类型//边的定义typedef struct ENode* PtrToENode;struct ENode{Vertex V1,V2;//有向边<V1,V2>WeightType Weight;//权重 };typedef PtrToENode Edge;MGraph CreateGraph(int VertexNum){//初始化一个有VertexNum个顶点但没有边的图Vertex V,W;MGraph Graph;Graph=(MGraph)malloc(sizeof(struct GNode));//建立图Graph->Nv= VertexNum;Graph->Ne=0;//初始化邻阶矩阵//注意:这里默认的编号从0开始,到(Graph->Nv-1) for(V=0;V<Graph->Ne;V++){ for(W=0;W<Graph->Nv;W++){ Graph->G[V][W]=INFINTY; } }return Graph;}void InsertEdge(MGraph Graph,Edge E){//插入边<V1,V2>Graph->G[E->V1][E->V2]=E->Weight; }MGraph BuildGraph(){MGraph Graph;Edge E;Vertex V;int Nv,i;scanf("%d",&Nv);//读入顶点数 Graph=CreateGraph(Nv);//初始化有Nv个顶点但没有边的图scanf("%d",&(Graph->Ne));//读入边数if(Graph->Ne!=0){//如果有边E=(Edge)malloc(sizeof(struct ENode));//建立边结点//读入边,格式为“起点 终点 权重”,插入邻阶矩阵for(i=0;i<Graph->Ne ;i++){scanf("%d %d %d\n",&E->V1 ,&E->V2 ,&E->Weight );//注意:如果权重不是整数,Weight的读入格式要改InsertEdge(Graph,E); }}//如果顶点有数据的话,读入数据for(V=0;V<Graph->Nv ;V++){scanf("%c",&(Graph->Data[V]));}return Graph;}void out(MGraph Graph){Vertex V,W;for(V=0;V<Graph->Nv ;V++){for(W=0;W<Graph->Nv ;W++){printf("%d ",Graph->G[V][W]);}printf("\n");}for(V=0;V<Graph->Nv;V++){printf("%c ",Graph->Data[V]);}printf("\n");}int main(){freopen("C:\\Users\\DELL\\Desktop\\新建文件夹 (2)\\text.txt","r",stdin);MGraph Graph;Graph=BuildGraph();out(Graph);free(Graph); return 0;}

0 0
原创粉丝点击