前言
图的构造方法通常有两种,一种是用邻接矩阵,一种是用邻接表。邻接矩阵不涉及链表的操作,所以使用起来会比较方便,但是对于较为稀疏的图而言,邻接矩阵会浪费很多空间。而对于静态数组构建的邻接矩阵而言,这更加是一种空间的浪费。
本文给出动态数组的邻接矩阵构造方法。
思路
对于图中一个顶点的存储数据,用一维动态数组。对于边的权值矩阵,用二维动态数组。
实现
c语言代码实现
#include<stdio.h>
#include<stdlib.h>
#define INFINITY 1000000;
typedef int WeightType;
typedef int DataType;
typedef struct GNode *PtrToGNode;
typedef PtrToGNode MGraph;
struct GNode
{
int Nv;
int Ne;
WeightType **G;
DataType *Data
};
MGraph CreateGraph(int Nv)
{
int i,j;
MGraph M = (MGraph)malloc(sizeof(struct GNode));
M->Nv = Nv;
M->Ne = 0;
M->G = (WeightType**)malloc(Nv*sizeof(WeightType*)); //row
for(i=0; i<Nv; i++)
M->G[i] = (WeightType *)malloc(Nv*sizeof(WeightType)); //column
M->Data = (DataType *)malloc(Nv*sizeof(DataType));
for(i=0; i<M->Nv; i++)
{
for(j=0; j<M->Nv; j++)
M->G[i][j] = INFINITY;
}
return M;
}
最后,创作不易,希望大家能顺手点个赞。如果觉得有帮助,可以加个收藏,给作者更大的创作动力