Figure (1)-adjacency matrix

Written in the front: This article writes the data structure realized by the adjacency matrix-----figure

 

(1) The composition of the graph realized by the adjacency matrix is ​​as follows

 

The graph is composed of vertices (Vertex) and edges (Edge) .

(2) Use a table to draw the connection method of Vertex

1 means that the two vertices are connected, and 0 means that there is no connection.

(3) The code realizes this diagram:

 

#include <iostream>
using namespace std;

#define MAX_VERTEXS (20)

class Vertex   //顶点
{
public:
	Vertex(char lab) :label(lab)
	{}

private:
	char label;
};

class Graph  //图 
{
public:
	Graph();
	~Graph();

	void addVertex(char lab);      //添加顶点
	void addEdge(int start,int end); //添加边
	void printMatrix();

private:
	Vertex * vertexList[MAX_VERTEXS];  //用来保存加入进来的顶点
	int nVertexs;  //当前顶点的个数
	int adjMat[MAX_VERTEXS][MAX_VERTEXS]; //二维数组来表示顶点的连接方式

};

Graph::Graph()
{
	nVertexs = 0;

	for (int i = 0; i < MAX_VERTEXS; i++)
		for (int j = 0; j < MAX_VERTEXS; j++)
			adjMat[i][j] = 0;
}
Graph::~Graph()
{
	for (int i = 0; i < nVertexs; i++)
		delete vertexList[i];
}

void Graph::addVertex(char lab)
{
	vertexList[nVertexs++] = new Vertex(lab);
}

void Graph::addEdge(int start, int end)
{
	adjMat[start][end] = 1;  //边是对称的
	adjMat[end][start] = 1;
}

void Graph::printMatrix()
{
	for (int i = 0; i < nVertexs; i++)
	{
		for (int j = 0; j < nVertexs; j++)
			cout << adjMat[i][j];

		cout << endl;
	}
		

}


int main()
{
	Graph gh;

	//添加顶点
	gh.addVertex('A');//0
	gh.addVertex('B');//1
	gh.addVertex('C');//2
	gh.addVertex('D');//3
	gh.addVertex('E');//4

	//添加边
	gh.addEdge(0,1); //A-B
	gh.addEdge(0,3); //A-D
	gh.addEdge(1,0); //B-A
	gh.addEdge(1,4); //B-E
	gh.addEdge(2,4); //C-E
	gh.addEdge(3,0); //D-A
	gh.addEdge(3,4); //D-E
	gh.addEdge(4,3); //E-D
	gh.addEdge(4,2); //E-C

	gh.printMatrix();


	return 0;
}

operation result:

 

 

Guess you like

Origin blog.csdn.net/weixin_40204595/article/details/108710449