用邻接矩阵存储一个的图 cpp实现
时间: 2024-03-26 16:42:32 浏览: 30
以下是使用 C++ 实现邻接矩阵存储无向图的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
const int MAXN = 100;
int n, m; // n 表示节点数,m 表示边数
int graph[MAXN][MAXN]; // 邻接矩阵,graph[i][j] 表示 i 和 j 之间是否有边
int main() {
cin >> n >> m;
// 初始化邻接矩阵
memset(graph, 0, sizeof(graph));
// 读入边
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u][v] = graph[v][u] = 1; // 无向图需要将两个方向都设置为 1
}
// 输出邻接矩阵
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << graph[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
在这个示例代码中,我们使用二维数组来表示邻接矩阵,并且使用了 memset 函数来初始化邻接矩阵。输入节点数和边数后,读入每一条边,并将邻接矩阵中对应的位置设置为 1。最后输出邻接矩阵。