图,包含顶点和边,在C++里面可以用类来表示
邻接矩阵吧图转化为二维矩阵,当图比较稀疏时可以用邻接表。
#include<iostream>
#define MAX_VERTS 20
using namespace std;
class Vertex{
public:
Vertex(char label){ Label = label; }
private:
char Label;
};
class Graph{
public:
Graph();
~Graph();
void addVertex(char lab);
void addEdge(int start, int end);
void printMatrix();
private:
Vertex* vertexList[MAX_VERTS];
int nVerts;//顶点个数
int adjMat[MAX_VERTS][MAX_VERTS];
};
Graph::Graph(){
nVerts = 0;
for (int i = 0; i < MAX_VERTS; i++){
for (int j = 0; j < MAX_VERTS; j++){
adjMat[i][j] = 0;
}
}
}
void Graph::addVertex(char lab){
vertexList[nVerts++] = 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 < nVerts; i++){
for (int j = 0; j < nVerts; j++){
cout << adjMat[i][j] << " ";
}
cout << endl;
}
}
Graph::~Graph(){
for (int i = 0; i < nVerts; i++){
delete vertexList[i];
}
}
int main(){
cout << "测试邻接矩阵:" << endl;
Graph g;
g.addVertex('A');//0
g.addVertex('B');//1
g.addVertex('C');//2
g.addVertex('D');//3
g.addVertex('E');//4
g.addEdge(0, 1);
g.addEdge(0, 3);
g.addEdge(1, 0);
g.addEdge(1, 4);
g.addEdge(2, 4);
g.addEdge(3, 0);
g.addEdge(3, 4);
g.addEdge(4, 1);
g.addEdge(4, 2);
g.addEdge(4, 3);
g.printMatrix();
system("pause");
return 0;
}
总结:我们可以使用邻接矩阵表示图,但是当图比较稀疏时,邻接矩阵有很多零,这样就造成浪费,所以可以用邻接表来表示图。