The storage of adjacency matrices is more convenient and easier to understand than adjacency tables.
The adjacency matrix uses a two-dimensional array matrix to store the relationship of every two points. If there is an edge between the two point m,n, set the array matrix[]m[m] to 1, otherwise set to 0.
If you have the right, matrix[m]n[] is set to a weight, defining a large or small number (as long as you do not conflict with a weight value), indicating that it is not connected.
The spatial complexity is O (v^2), which is suitable for dense graphs.
adjacency table O (v+e), suitable for comparison of sparse graphs.
GraphMatrix.h
#include <iostream> #include <cstdio> #include <iomanip>//Std::setw#define No_edge ( -1) using names Pace std;//directed graph class Graphmatrix{public:~graphmatrix (), void Creategraph (), void Printgraph ();p rivate://1. Input fixed-point number void Inputvertexcount ();//2. Generates a fixed-point array void Makevertexarray ();//3. Input number of sides void Inputedgecount ();//4. The starting point of the input edge is void inputedgeinfo ();//5. Add edge nodes to the corresponding list of void addedgetolist (int vfrom, int weight, int vTo);p rivate:int m_vcount;int m_ecount;int** M_vvertex;}; Graphmatrix::~graphmatrix () {for (int i = 0; i < M_vcount; ++i) {delete m_vvertex[i];} Delete[] M_vvertex;} void Graphmatrix::inputvertexcount () {cout << "Please input count of vertex:"; cin >> M_vcount;} void Graphmatrix::makevertexarray () {M_vvertex = new Int*[m_vcount];for (int i = 0; i < M_vcount; ++i) {M_vvertex[i] = NE W Int[m_vcount];} for (int i = 0, i < M_vcount; ++i) {for (int j = 0; j < M_vcount; ++j) {m_vvertex[i][j] = No_edge;}} void Graphmatrix::inputedgecount () {cout << "please input COunt of Edge: "; cin >> M_ecount;} void Graphmatrix::inputedgeinfo () {cout << "please input edge information:" << endl;for (int i = 0; i < M_ecount; ++i) {cout << "the Edge" << I << ":" << endl;//start int from = 0;cout << "from:"; Cin >> from;//weight int weight = 0;cout << "Weight:"; cin >> weight;//end int to = 0;cout << "to:"; Cin >> to ; cout << endl;addedgetolist (from, weight, to);}} void graphmatrix::addedgetolist (int vfrom, int weight, int vTo) {M_vvertex[vfrom][vto] = weight;} void Graphmatrix::p rintgraph () {for (int i = 0, i < M_vcount; ++i) {for (int j = 0; j < M_vcount; ++j) {cout << s ETW (3) << m_vvertex[i][j] << "";} cout << Endl;}} Process Control//*************************** void Graphmatrix::creategraph () {inputvertexcount (); Makevertexarray (); Inputedgecount (); InpuTedgeinfo ();}
Main.cpp
Test for Graphmartrix#include "GraphMatrix.h" #include <cstdlib>int main () {Graphmatrix graph; Graph.creategraph (); Graph.printgraph (); System ("pause"); return 0;}
If there is a picture as follows
Operation Result:
Algorithm and data structure base 9:c++ realization of graph adjacency matrix storage