今天学到图论了,一切都要好好学习呢!今天用邻接矩阵存储图,想存一个这样的图。
本博文源于浙江大学《数据结构》。函数包括创建图结点,插入边,构造图,下面给出全部源码,文末附有测试案例结果!
#include<stdio.h>
#include<stdlib.h>
#define MaxVertexNum 10
typedef int WeightType;
typedef int DataType;
typedef struct GNode *PtrToGNode;
struct GNode {
int Nv; //一张图的顶点数
int Ne; //一张图的边数
WeightType G[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum];//存顶点的数据
};
typedef PtrToGNode MGraph;//以邻接矩阵存储的图类型
//初始化一个有VertexNum 个顶点但没有边的图
typedef int Vertex;//用顶点下标表示顶点,为整型
MGraph CreateGraph(int 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->Nv;V++)
for(W=0; W<Graph->Nv;W++)
Graph->G[V][W] = 0;
return Graph;
}
typedef struct ENode *PtrToENode;
struct ENode {
Vertex V1,V2;//有向边<V1,V2>
WeightType Weight;//权值
};
typedef PtrToENode Edge;
void InsertEdge(MGraph Graph, Edge E)
{
Graph->G[E->V1][E->V2] = E->Weight;
Graph->G[E->V2][E->V1] = E->Weight;
}
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int Nv,i;
scanf("%d",&Nv);
Graph = CreateGraph(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",&E->V1,&E->V2,&E->Weight);
InsertEdge(Graph, E);
}
}
/*
for(V=0;V<Graph->Nv;V++)
scanf(" %c",&(Graph->Dadta[V]));
*/
return Graph;
}
int main()
{
MGraph Graph = BuildGraph();
int Nv = Graph->Nv;
for(int i=0;i<Nv;i++)
{
for(int j=0;j<Nv;j++)
printf("%d ",Graph->G[i][j]);
printf("\n");
}
return 0;
}