图的存储结构—————邻接矩阵

 1 #include "stdio.h"
 2 #include "stdlib.h"
 3 #define Max_vertex_num 20//顶点数目最大值
 4 #define INFINITY 32768
 5 typedef char VertexData;//顶点数据类型
 6 typedef int EdgeType;//边权数据类型
 7 typedef struct {
 8 VertexData vertex[Max_vertex_num];//一维数组存储顶点信息
 9 EdgeType edge[Max_vertex_num][Max_vertex_num];//存储顶点之间关联关系的二维数组
10 int vexnum, arcnum;//图中顶点数和弧数
11 }MGraph;
12 //无向图的邻接矩阵是对称矩阵,可以采用特殊矩阵的压缩法,只存储下三角即可
13 //n个顶点需1+2+...+n=n(n-1)/2个存储空间,而有向图的邻接矩阵不一定是对阵矩阵,
14 //故需要n*n个存储空间
15 //对于稀疏图来说,不适于用邻接矩阵来存储,会造成空间的浪费
16 //采用邻接矩阵创建有向图
17 //1.求顶点位置函数
18 int LocateVertex(MGraph* G, VertexData v) {
19 int j=-1, k;
20 for(k=0;k<G->vexnum;k++)
21 if (G->vertex[k] == v) {
22 j = k;
23 break;
24 }
25 return j;
26 }
27 //创建有向图
28 void CreateDN(MGraph *G) {
29 int i, j, k,weight;
30 VertexData v1, v2;
31 scanf_s("%d,%d", &G->vexnum, &G->arcnum);
32 for (i = 0; i < G->vexnum; i++)
33 for (j = 0; j < G->vexnum; j++)
34 G->edge[i][j] = INFINITY;
35 for (i = 0; i < G->vexnum; i++)
36 scanf_s("%c", &G->vertex[i]);
37 for (k = 0; k < G->arcnum; k++) {
38 printf("输入顶点<v1,v2>及其权值:\n");
39 scanf_s("%c,%c,%d", &v1, &v2, &weight);
40 i = LocateVertex(G, v1);
41 j = LocateVertex(G, v2);
42 G->edge[i][j] = weight;
43 } 
44 }
45 int main() {
46 MGraph G;
47 CreateDN(&G);
48 system("pause");
49 return 0;
50 }

 

posted @ 2021-08-20 17:34  #Lorraine#  阅读(186)  评论(0编辑  收藏  举报