用邻接矩阵方式建立图、简化化版
//用邻接矩阵表示图
#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 20
typedef int WeightType;
typedef char DataType;
typedef struct GNode *PtrToGNode;
typedef PtrToGNode MGraph; //以邻接矩阵存储的图类型
struct GNode {
int Nv; //顶点数
int Ne; //边数
WeightType G[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum]; //存顶点的数据
};
//初始化一个有VertexNUm个顶点但没有边的图
typedef int Vertex; //用顶点下标表示顶点,为整型
MGraph CreateGraph(int VertexNum)
{
Vertex v, w;
struct GNode* Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph ->Nv = MaxVertexNum;
Graph ->Ne = 0;
//这里的默认编号从0开始,到(Graph->Nv - 1)
for (v = 0; v < Graph->Nv; v++)
for (w = 0; w < Graph->Ne; w++)
Graph->G[v][w] = 0;
return Graph;
}
//向MGraph中插入边
typedef struct ENode *PtrToENode;
struct ENode {
Vertex v1, v2; //有向边<v2, v1>
WeightType Weight; //权重
};
typedef PtrToENode Edge;
void InsertEdge(MGraph Graph, Edge E)
{
//插入边<v1, v2>
Graph->G[E -> v1][E->v2] = E->Weight;
//插入边<v2, v1>
Graph->G[E->v2][E->v1] = E->Weight;
}
//完整地建立一个MGraph
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int Nv, i;
scanf_s("%d", &Nv);
Graph = CreateGraph(Nv);
scanf_s("%d", &(Graph->Ne));
if (Graph->Ne != 0)
{
E = (Edge)malloc(sizeof(struct ENode));
for (i = 0; i < Graph->Ne; i++)
scanf_s("%d %d %d", &E->v1, &E->v2, &E->Weight);
InsertEdge(Graph, E);
}
//
for (V = 0; V < Graph->Nv; V++)
scanf_s(" %c", Graph->Data[V]);
return Graph;
}
int main()
{
return 0;
}
简化版
//用邻接矩阵表示图
#include <stdio.h>
#include <stdlib.h>
#define MaxN 20
int G[MaxN][MaxN], Nv, Ne;
void BuildGraph()
{
int i , j, v1, v2, w;
scanf("%d", &Nv);
for (i = 0; i < Nv; i++)
for (j = 0; j < Nv; j++)
G[i][j] = 0;
scanf_s("%d", &Ne);
for (i = 0; i < Ne; i++)
{
scanf_s("%d %d %d", &v1, &v2, &w);
G[v1][v2] = w; //InsertEdge
G[v2][v1] = w;
}
}