图-邻接矩阵
下面是一个完整的C++实现手写邻接矩阵表示图的代码。邻接矩阵是一种常见的图的表示方法,其中矩阵的行和列分别代表图中的顶点,矩阵中的值表示顶点之间是否存在边。
参考代码
#include <iostream>
#include <vector>
class Graph {
private:
int numVertices; // 图中顶点的数量
std::vector<std::vector<int>> adjMatrix; // 邻接矩阵
public:
// 构造函数
Graph(int vertices) : numVertices(vertices) {
adjMatrix.resize(numVertices, std::vector<int>(numVertices, 0));
}
// 添加边
void addEdge(int src, int dest) {
if (src >= 0 && src < numVertices && dest >= 0 && dest < numVertices) {
adjMatrix[src][dest] = 1;
adjMatrix[dest][src] = 1; // 如果是无向图,需要对称设置
} else {
std::cerr << "Invalid vertex index!" << std::endl;
}
}
// 删除边
void removeEdge(int src, int dest) {
if (src >= 0 && src < numVertices && dest >= 0 && dest < numVertices) {
adjMatrix[src][dest] = 0;
adjMatrix[dest][src] = 0; // 如果是无向图,需要对称设置
} else {
std::cerr << "Invalid vertex index!" << std::endl;
}
}
// 打印邻接矩阵
void print() const {
for (int i = 0; i < numVertices; ++i) {
for (int j = 0; j < numVertices; ++j) {
std::cout << adjMatrix[i][j] << " ";
}
std::cout << std::endl;
}
}
// 检查两个顶点之间是否有边
bool hasEdge(int src, int dest) const {
if (src >= 0 && src < numVertices && dest >= 0 && dest < numVertices) {
return adjMatrix[src][dest] == 1;
} else {
std::cerr << "Invalid vertex index!" << std::endl;
return false;
}
}
};
int main() {
Graph graph(5); // 创建一个包含5个顶点的图
graph.addEdge(0, 1); // 添加边 0-1
graph.addEdge(0, 4); // 添加边 0-4
graph.addEdge(1, 2); // 添加边 1-2
graph.addEdge(1, 3); // 添加边 1-3
graph.addEdge(1, 4); // 添加边 1-4
graph.addEdge(2, 3); // 添加边 2-3
graph.addEdge(3, 4); // 添加边 3-4
std::cout << "Adjacency Matrix:" << std::endl;
graph.print();
std::cout << "Is there an edge between 1 and 3? " << (graph.hasEdge(1, 3) ? "Yes" : "No") << std::endl;
std::cout << "Is there an edge between 2 and 4? " << (graph.hasEdge(2, 4) ? "Yes" : "No") << std::endl;
graph.removeEdge(1, 3); // 删除边 1-3
std::cout << "Adjacency Matrix after removing edge 1-3:" << std::endl;
graph.print();
return 0;
}
代码说明:
图的表示:
使用std::vector<std::vector>来表示邻接矩阵。
numVertices表示图中顶点的数量。
构造函数:
初始化邻接矩阵,所有值初始化为0,表示没有边。
添加边:
addEdge(int src, int dest):在顶点src和dest之间添加一条边。如果是无向图,需要对称设置。
删除边:
removeEdge(int src, int dest):删除顶点src和dest之间的边。如果是无向图,需要对称设置。
打印邻接矩阵:
print():打印邻接矩阵的内容。
检查边是否存在:
hasEdge(int src, int dest):检查顶点src和dest之间是否存在边。
输出结果
Adjacency Matrix:
0 1 0 0 1
1 0 1 1 1
0 1 0 1 0
0 1 1 0 1
1 1 0 1 0
Is there an edge between 1 and 3? Yes
Is there an edge between 2 and 4? No
Adjacency Matrix after removing edge 1-3:
0 1 0 0 1
1 0 1 0 1
0 1 0 1 0
0 0 1 0 1
1 1 0 1 0