图的邻接矩阵完整代码
时间: 2024-06-05 08:05:11 浏览: 9
邻接矩阵是一种表示图的方法,它用一个矩阵来表示图中各个顶点之间的连接情况。以下是邻接矩阵的完整代码示例:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 100; // 最大顶点数
class Graph {
private:
int vertexCount; // 顶点数
int edgeCount; // 边数
int adjMatrix[MAX_SIZE][MAX_SIZE]; // 邻接矩阵
public:
Graph(int vCount) {
vertexCount = vCount;
edgeCount = 0;
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
adjMatrix[i][j] = 0;
}
}
}
void addEdge(int i, int j) {
adjMatrix[i][j] = 1;
adjMatrix[j][i] = 1;
edgeCount++;
}
void removeEdge(int i, int j) {
adjMatrix[i][j] = 0;
adjMatrix[j][i] = 0;
edgeCount--;
}
bool isEdge(int i, int j) const {
return adjMatrix[i][j] == 1;
}
int getVertexCount() const {
return vertexCount;
}
int getEdgeCount() const {
return edgeCount;
}
};
int main() {
Graph g(5); // 创建5个顶点的图
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
cout << "邻接矩阵:" << endl;
for (int i = 0; i < g.getVertexCount(); i++) {
for (int j = 0; j < g.getVertexCount(); j++) {
cout << g.isEdge(i, j) << " ";
}
cout << endl;
}
return 0;
}
```
以上代码实现了一个 Graph 类,其中包含了邻接矩阵的相关操作。通过创建 Graph 对象并调用其方法,可以方便地对图进行操作。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)