用邻接矩阵表示图

#pragma warning(disable:4996)
#include<malloc.h>
#include<stdio.h>
#define MaxVertexNum 100 //最大顶点数设为100
#define INFINITY 65535 //最大值为65535
typedef int Vertex; //用顶点下标表示顶点,为整型
typedef int WeightType;
typedef char DataType;

//边的定义
typedef struct ENode* PtrToENode;
struct ENode {
Vertex V1, V2; //有向边<V1,V2>
WeightType Weight; //权重
};
typedef PtrToENode Edge;

//图结点的定义
typedef struct GNode* PtrToGNode;
struct GNode {
int Nv; //顶点数
int Ne; //边数
WeightType G[MaxVertexNum][MaxVertexNum]; //邻接矩阵
DataType Data[MaxVertexNum]; //存顶点的数据
};
typedef PtrToGNode MGraph; //以邻接矩阵存储的图类型

MGraph CreateGraph(int VertexNum) {
//初始化一个有Vertex个顶点但没有边的图
Vertex V, W;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));//建立图
Graph->Nv = VertexNum;
Graph->Ne = 0;
//初始化邻接矩阵
//这里默认编号从0开始
for (V = 0; V < Graph->Nv; V++) {
for (W = 0; W < Graph->Ne; W++) {
Graph->G[V][W] = INFINITY;
}
}
return Graph;
}

void InsertEdge(MGraph Graph, Edge E) {
//插入边
Graph->G[E->V1][E->V2] = E->Weight;
//若是无向图,还要插入边<V2,V1>
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); //初始化有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);
//如果权重不是整型,weight的读入格式要改
InsertEdge(Graph, E);
}
}
//如果顶点有数据,则读入顶点
for (V = 0; V < Graph->Nv; V++) {
scanf("%c", &(Graph->Data[V]));
}
return Graph;
}

原文地址:https://www.cnblogs.com/wei1349/p/13510971.html