下面是一个简单的C++实例,演示了如何使用邻接矩阵和邻接表来表示图。这里以无向图为例:
邻接矩阵:
#include <iostream>
#include <vector>
class GraphMatrix {
private:
int vertices; // 顶点数
std::vector<std::vector<int>> adjacencyMatrix; // 邻接矩阵
public:
GraphMatrix(int V) : vertices(V) {
// 初始化邻接矩阵,全部置为0
adjacencyMatrix.resize(vertices, std::vector<int>(vertices, 0));
}
// 添加边
void addEdge(int v1, int v2) {
adjacencyMatrix[v1][v2] = 1;
adjacencyMatrix[v2][v1] = 1;
}