图的邻接矩阵
结构体:
//图结点
typedef struct GNode {
int Nv; //顶点点个数
int Ne; //边数
weightType G[MaxVertexNum][MaxVertexNum];
}GNode, *MGraph;
//边结点
typedef struct ENode {
Vertex V1, V2;
weightType Weight;
}*Edge;
初始化图(图不可为空):
//初始化所顶点
MGraph CreateGraph(int VertexNum)
{
MGraph Graph;
Vertex V,W;
Graph = (MGraph)malloc(sizeof(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[E->V2][E->V1]; = E->Weight;
}
建图
//建图
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int NV;
printf("请输入节点个数:\n");
scanf("%d",&(Graph->Nv));
Graph = CreateGraph(Graph->Nv);
printf("请输入边数:\n");
scanf("%d", &(Graph->Ne));
if(Graph->Ne !=0 ) {
E = (Edge)malloc(sizeof(Edge));
for(int i =0;i<Graph->Ne;i++){
printf("输入v1编号、v2编号和权值:\n");
scanf("%d %d %d",&(E->V1), &(E->V2),&(E->Weight));
InsertEdge(Graph,E);
}
}
return Graph;
}
完整代码:
#include<stdio.h>
#include<malloc.h>
#define MaxVertexNum 100
typedef int weightType ;
typedef int Vertex;
//图结点
typedef struct GNode {
int Nv; //顶点点个数
int Ne; //边数
weightType G[MaxVertexNum][MaxVertexNum];
}GNode, *MGraph;
//边结点
typedef struct ENode {
Vertex V1, V2;
weightType Weight;
}*Edge;
//初始化所顶点
MGraph CreateGraph(int VertexNum)
{
MGraph Graph;
Vertex V,W;
Graph = (MGraph)malloc(sizeof(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[E->V2][E->V1]; = E->Weight;
}
//建图
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int NV;
printf("请输入节点个数:\n");
scanf("%d",&(Graph->Nv));
Graph = CreateGraph(Graph->Nv);
printf("请输入边数:\n");
scanf("%d", &(Graph->Ne));
if(Graph->Ne !=0 ) {
E = (Edge)malloc(sizeof(Edge));
for(int i =0;i<Graph->Ne;i++){
printf("输入v1编号、v2编号和权值:\n");
scanf("%d %d %d",&(E->V1), &(E->V2),&(E->Weight));
InsertEdge(Graph,E);
}
}
return Graph;
}
int main()
{
int Num;
MGraph Graph;
Graph = BuildGraph();
Vertex V,W;
// for(V = 0;V < Graph->Nv;V++)
// {
// for(W = 0;W < Graph->Nv;W++)
// printf("%d ",Graph->G[V][W]);
// printf("\n");
// }
return 0;
}