1 //用邻接矩阵表示图 2 #include <stdio.h> 3 #include <stdlib.h> 4 #define MaxVertexNum 20 5 6 typedef int WeightType; 7 typedef char DataType; 8 typedef struct GNode *PtrToGNode; 9 typedef PtrToGNode MGraph; //以邻接矩阵存储的图类型 10 11 struct GNode { 12 int Nv; //顶点数 13 int Ne; //边数 14 WeightType G[MaxVertexNum][MaxVertexNum]; 15 DataType Data[MaxVertexNum]; //存顶点的数据 16 }; 17 18 19 20 //初始化一个有VertexNUm个顶点但没有边的图 21 typedef int Vertex; //用顶点下标表示顶点,为整型 22 MGraph CreateGraph(int VertexNum) 23 { 24 Vertex v, w; 25 struct GNode* Graph; 26 Graph = (MGraph)malloc(sizeof(struct GNode)); 27 Graph ->Nv = MaxVertexNum; 28 Graph ->Ne = 0; 29 30 //这里的默认编号从0开始,到(Graph->Nv - 1) 31 for (v = 0; v < Graph->Nv; v++) 32 for (w = 0; w < Graph->Ne; w++) 33 Graph->G[v][w] = 0; 34 35 return Graph; 36 } 37 38 //向MGraph中插入边 39 typedef struct ENode *PtrToENode; 40 struct ENode { 41 Vertex v1, v2; //有向边<v2, v1> 42 WeightType Weight; //权重 43 }; 44 typedef PtrToENode Edge; 45 46 void InsertEdge(MGraph Graph, Edge E) 47 { 48 //插入边<v1, v2> 49 Graph->G[E -> v1][E->v2] = E->Weight; 50 51 //插入边<v2, v1> 52 Graph->G[E->v2][E->v1] = E->Weight; 53 } 54 55 //完整地建立一个MGraph 56 MGraph BuildGraph() 57 { 58 MGraph Graph; 59 Edge E; 60 Vertex V; 61 int Nv, i; 62 scanf_s("%d", &Nv); 63 Graph = CreateGraph(Nv); 64 scanf_s("%d", &(Graph->Ne)); 65 if (Graph->Ne != 0) 66 { 67 E = (Edge)malloc(sizeof(struct ENode)); 68 for (i = 0; i < Graph->Ne; i++) 69 scanf_s("%d %d %d", &E->v1, &E->v2, &E->Weight); 70 InsertEdge(Graph, E); 71 } 72 73 // 74 for (V = 0; V < Graph->Nv; V++) 75 scanf_s(" %c", Graph->Data[V]); 76 77 return Graph; 78 } 79 80 81 82 int main() 83 { 84 85 86 return 0; 87 }
简化版:
1 //用邻接矩阵表示图 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 #define MaxN 20 6 int G[MaxN][MaxN], Nv, Ne; 7 void BuildGraph() 8 { 9 int i , j, v1, v2, w; 10 scanf("%d", &Nv); 11 12 for (i = 0; i < Nv; i++) 13 for (j = 0; j < Nv; j++) 14 G[i][j] = 0; 15 scanf_s("%d", &Ne); 16 for (i = 0; i < Ne; i++) 17 { 18 scanf_s("%d %d %d", &v1, &v2, &w); 19 20 G[v1][v2] = w; //InsertEdge 21 G[v2][v1] = w; 22 } 23 }