c++设计程序:当输入无向图的相邻点连接情况时,输出邻接矩阵和邻接表
时间: 2023-07-15 15:13:35 浏览: 86
以下是C++程序设计,根据输入的无向图的相邻点连接情况,输出邻接矩阵和邻接表:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 邻接矩阵
void adjacency_matrix(vector<vector<int>>& graph, int n) {
vector<vector<int>> adj_matrix(n, vector<int>(n, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (graph[i][j]) {
adj_matrix[i][j] = 1;
adj_matrix[j][i] = 1;
}
}
}
cout << "邻接矩阵:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << adj_matrix[i][j] << " ";
}
cout << endl;
}
}
// 邻接表
void adjacency_list(vector<vector<int>>& graph, int n) {
vector<vector<int>> adj_list(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (graph[i][j]) {
adj_list[i].push_back(j);
adj_list[j].push_back(i);
}
}
}
cout << "邻接表:" << endl;
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;
}
}
int main() {
int n; // 无向图中点的个数
cout << "请输入无向图中点的个数:";
cin >> n;
vector<vector<int>> graph(n, vector<int>(n, 0)); // 初始化图
// 输入相邻点连接情况
int p1, p2;
cout << "请输入相邻点连接情况(以-1结束):" << endl;
while (true) {
cin >> p1 >> p2;
if (p1 == -1 || p2 == -1) {
break;
}
graph[p1][p2] = 1;
graph[p2][p1] = 1;
}
// 输出邻接矩阵和邻接表
adjacency_matrix(graph, n);
adjacency_list(graph, n);
return 0;
}
```
运行程序后,按照提示输入无向图中点的个数和相邻点连接情况,程序会输出邻接矩阵和邻接表。
阅读全文