一个无向图 V(G1)={0,1,2,3,4,5,6,7,8,9,10} 边集合 E(G1)={(0,1),(0,2),(0,3),(1,4),(1,5),(2,5),(2,6),(3,7),(6,8),(6,9),(7,10)}请用c++写出它邻接矩阵与邻接表的代码
时间: 2023-06-19 09:06:15 浏览: 84
邻接矩阵的代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 11;
vector<vector<int>> adj_matrix(n, vector<int>(n, 0)); // 初始化 n * n 的邻接矩阵
vector<pair<int, int>> edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {2, 5}, {2, 6}, {3, 7}, {6, 8}, {6, 9}, {7, 10}};
// 填充邻接矩阵
for (auto edge : edges) {
int u = edge.first;
int v = edge.second;
adj_matrix[u][v] = 1;
adj_matrix[v][u] = 1;
}
// 打印邻接矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << adj_matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
邻接表的代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 11;
vector<vector<int>> adj_list(n);
vector<pair<int, int>> edges = {{0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {2, 5}, {2, 6}, {3, 7}, {6, 8}, {6, 9}, {7, 10}};
// 填充邻接表
for (auto edge : edges) {
int u = edge.first;
int v = edge.second;
adj_list[u].push_back(v);
adj_list[v].push_back(u);
}
// 打印邻接表
for (int i = 0; i < n; i++) {
cout << i << ": ";
for (int j = 0; j < adj_list[i].size(); j++) {
cout << adj_list[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
阅读全文