图的邻接矩阵的存储方式是用两个数组来表示图。一个一维数组存储图的顶点信息一个二维数组存储图中的边的信息。假设一维数组为vexs[maxvex],二维数组为arc[maxvex][maxvex],maxvex=100。
在无向图中:
- 若顶点vi与vj之间的权重为w则arc[i][j]=w;
- 若顶点vi与vj之间无连接则arc[i][j]=65535;
- 若顶点vi与vi之间则arc[i][j]=0。
由于是无向图则arc[i][j]=arc[j][i]。
在有向图中同上只不过arc[i][j]!=arc[j][i],要给arc[j][i]赋予自己的权值。
#ifndef Graph_H
#define Graph_H
#include<fstream>
#include<iostream>
#define MAXVEX 100
#define INFINITY 65535
typedef int VertexType;
typedef int EdgeType;
typedef int ShortPathTable[MAXVEX];
typedef int Pathmatirx[MAXVEX];
class Graph
{
public:
Graph();
~Graph();
void CreateMGraph();
public:
VertexType vexs[MAXVEX];
EdgeType arc[MAXVEX][MAXVEX];
int numVertexs, numEdge;
private:
};
#endif // !Graph_H
#include"Graph.h"
using namespace std;
Graph::Graph()
{
}
Graph::~Graph()
{
}
void Graph::CreateMGraph()
{
int i, j, k, w;
cout << "输入顶点数和边数" << endl;
cin >> numVertexs >> numEdge;
for ( i = 0; i < numVertexs; i++)
{
vexs[i]=i;
}
ifstream infile;
infile.open("inputdata.txt");
for ( i = 0; i < numVertexs; i++)
{
for (j = 0;j < numVertexs;j++)
{
arc[i][j] = INFINITY;
}
}
for ( k = 0; k < numEdge; k++)
{
infile >> i >> j >> w;
arc[i][j] = w;
arc[j][i] = w;
}
infile.close();
for (i = 0;i < numVertexs;i++)
{
for (j = 0;j < numVertexs;j++)
{
cout << arc[i][j] << " ";
}
cout << endl;
}
}
代码中为无向图的邻接矩阵的存储,其中inputdata.txt存放着顶点与边的信息,读者可以自己设置。