图的建立——邻接矩阵
|Word Count:816|Reading Time:3mins|Post Views:
通过邻接矩阵实现图的存储
图的存储结构
通过邻接矩阵的方式建立图
邻接矩阵(Adjacency Matrix)的存储结构就是通过一维数组存储图中顶点的信息,用矩阵表示图中各个顶点的的临界关系,而矩阵通过一个二维数组表示。
图的分类及表示

图的矩阵中表示方法


在无向图中矩阵的表示


无向网中矩阵的表示


存储顶点信息的结构
存储图的信息时,要通过结构体来定义数据类型,以无向网为例定义如下:
1 2 3 4 5 6 7 8
| #define MAX_VEX 100 #define INF 65535 struct Graph{ char vexs[MAX_VEX]; int arc[MAX_VEX][MAX_VEX]; int numvex; int numarc; };
|
图信息的初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| void CreateGraph(Graph &G){ int vi, vj, w; cout << "please enter the number of vertexes and arcs : \n"; cin >> G.numvex >> G.numarc; for(int i = 0; i < G.numvex; i++){ printf("Please enter the NO.%d name of vex : ",i+1); cin >> G.vexs[i]; } for(int i = 0; i < G.numvex; i++){ for(int j = 0; j < G.numvex ;j++){ G.arc[i][j] = INF; } } cout << endl; for(int i = 0; i < G.numarc; i++){ cout<< "Enter the subscripts and weights from vertex vi to vertex vj : "; cin >> vi >> vj >> w; G.arc[vi][vj] = w; G.arc[vj][vi] = w; } }
|
完整实现过程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <iostream> #include <cstdio> #define MAX_VEX 100 #define INF 65535
using namespace std; struct Graph{ char vexs[MAX_VEX]; int arc[MAX_VEX][MAX_VEX]; int numvex,numarc; }; void CreateGraph(Graph &G){ int vi, vj, w; cout << "please enter the number of vertexes and arcs : \n"; cin >> G.numvex >> G.numarc; for(int i = 0; i < G.numvex; i++){ printf("Please enter the NO.%d name of vex : ",i+1); cin >> G.vexs[i]; } for(int i = 0; i < G.numvex; i++){ for(int j = 0; j < G.numvex ;j++){ G.arc[i][j] = INF; } } cout << endl; for(int i = 0; i < G.numarc; i++){ cout<< "Enter the subscripts and weights from vertex vi to vertex vj : "; cin >> vi >> vj >> w; G.arc[vi][vj] = w; G.arc[vj][vi] = w; } } void DispalyGraph(Graph G){ for(int i = 0; i < G.numvex; i++) cout << G.vexs[i] << " "; cout << endl; for(int i = 0; i < G.numvex; i++){ for(int j = 0; j < G.numvex; j++){ if(G.arc[i][j] == INF) printf("%6s", "∞"); else printf("%6d", G.arc[i][j]); } cout << endl; } } int main(){ Graph G; CreateGraph(G); DispalyGraph(G); return 0; }
|
实现结果
以下面的无向网为例:
