图-表示多对多的关系,一组顶点V(一个非空有限顶点集合),一组边E(一个有限边集合),边上有权重称为网络。用邻接矩阵(稠密图)或者邻接表(稀疏图)表示一个图。
一、邻接矩阵表示:
在Graph_M.h中:
#include"iostream"
using namespace std;
/******************邻接矩阵表示图**************************/
#define MaxVertexNum 128
#define WeightType int
typedef int Vertex;
typedef struct GNode *PtrToGNode;
struct GNode {
int Nv; //顶点数
int Ne; //边数
WeightType G[MaxVertexNum][MaxVertexNum]; //存储顶点的数据
};
typedef PtrToGNode MGraph;
typedef struct ENode *PtrToENode;
struct ENode
{
Vertex V1, V2; //有向边<V1,V2>
WeightType Weight; //权重
};
typedef PtrToENode Edge;
MGraph CreateGraph(int VertexNum);
void InsertEdge(MGraph Graph, Edge E);
MGraph BuildGraph();
void OutputGraph(MGraph Graph);
在Graph_M.cpp中:
#include"Graph_M.h"
/******************邻接矩阵表示图**************************/
MGraph CreateGraph(int VertexNum)
{
Vertex V, W;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for (V = 0; V < Graph->Nv; V++)
for (W = 0; W < Graph->Nv; W++)
Graph->G[V][W] = 0;
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;
cout << "Input Nv:\n"