邻接矩阵
//临接矩阵
#define MaxVertexNum 100
#define INFINITY 65535
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
typedef struct GNode *PtrToGNode;
struct GNode{ //定义图的结构体
int Nv; //顶点数
int Ne; //边数
WeightType G[MaxVertxeNum][MaxVertexNum]; //一个二维数组,用来存放每条边的信息(两条边有连接,并且有权值)
Datatype Data[MaxVertxeNum]; //节点的信息
};
typedef PtrToGNode Graph;
typedef struct ENode *PtrToENode;
struct ENode{ //定义边的信息
Vertx V1,V2; //V1为起点,V2为终点
WeightType Weight; //weight为权重
};
typedef PtrToENode Edge;
MGraph CreatrGraph(int VertexNum){ //创建一个带VertexNum个空顶点的图
MGraph Graph;
Vertex V,W;
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]=INFINITY; //初始化二维数组为INFINITY代表都是独立没有连接的点
return Graph;
}
void InsertEdge(MGraph Graph,Edge E){ //连接两个顶点,把权值赋值到二维数组中,代表连接
Graph->G[E->V1][E->V2]=E->Weight; //因为是无向图,需要把两条边都插入
Graph->G[E->V2][E->V1]=E->Weight;
}
MGrapg BuildGraph(){ //创建一个完整的图
MGraph Graph;
Edge E;
Vertex V;
int Nv,i;
scanf("%d",&Nv);
Graph=CreatGraph(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("%d",&Graph->Data[V]);
return Graph;
}
邻接表
//邻接表
#define MaxVertexNum 100
#define INFINITY 65535
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
typedef struct ENode *PtrToENode; ///边
struct ENode{
Vertex V1,V2;
WeightType Weight;
};
typedef PtrToENode Edge;
typedef struct AdjVNode *PtrToAdjVNode; //邻节点
struct AdjVNode {
Vertex AdjV;
WeightType Weight;
PtrToAdjVNode Next;
};
typedef struct VNode{ //顶点表头节点
PtrToAdjVNode FirstEdge;
DataType Data;
}AdjList [MaxVertexNum];
typedef struct GNode *PtrToGNode; //图
struct GNode{
int Nv,Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
LGraph CreatGraph(int VertexNum){ //创建一个
LGraph Graph;
Vertex V;
Graph=(LGraph)malloc(sizeof(struct GNode));
Graph->Nv=VertexNum;
Graph->Ne=0;
for(V=0;V<Graph->Nv;V++) //初始化表头指针
Graph->G[V].FirstEdge=NULL;
return Graph;
}
void InsertEdge(LGraph Graph,Edge E){ //插入边
PtrToAdjVNode NewNode;
NewNode=(PtrToAdjVNode)malloc(sizeof(struct AdjVNode)); //把顶点V2插入序号为V1的数组的后边,代表插入边<V1,V2>
NewNode->AdjV=E->V2;
NewNode->Weight=E->Weight;
NewNode->Next=Graph->G[E->V1].FirstEdge;
Graph->G[E->V1].FirstEdge=NewNode;
NewNode=(PtrToAdjVNode)malloc(sizeof(struct AdjVNode)); //无向表要插入边<V2,V1>
NewNode->AdjV=E->V1;
NewNode->Weight=E->Weight;
NewNode->Next=Graph->G[E->V2].FirstEdge;
Graph->G[E->V2].FirstEdge=NewNode;
}
LGraph BuildHraph(){ //完整表的构建
LGraph Graph;
Edge E;
int Nv,i;
scanf("%d",&Nv);
Graph=CreatGraph(Nv);
scanf("%d",&Graph->Ne);
if(Graph->Ne!=0){ //如果边不为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(i=0;i<Graph->Nv;i++) //顶点 有信息就插入信息
scanf("%d",&Graph->G[i].Data);
return Graph;
}