matrix[0][1] = matrix[1][0] = 1; matrix[0][2] = matrix[2][0] = 1; matrix[0][3] = matrix[3][0] = 1; matrix[1][4] = matrix[4][1] = 1; matrix[1][5] = matrix[5][1] = 1; matrix[2][5] = matrix[5][2] = 1; matrix[2][6] = matrix[6][2] = 1; matrix[3][7] = matrix[7][3] = 1; matrix[6][8] = matrix[8][6] = 1; matrix[6][9] = matrix[9][6] = 1; matrix[7][10] = matrix[10][7] = 1;把这个邻接矩阵转化为邻接表,用c++写出它的代码
时间: 2023-06-19 07:06:01 浏览: 113
ch7.rar_创建邻接矩阵_邻接矩阵_邻接矩阵c++_邻接表
可以使用 vector 来实现邻接表,代码如下:
```c++
#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 11; // 节点个数
vector<int> adjList[MAXN]; // 邻接表
int main() {
int matrix[MAXN][MAXN] = {{0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}};
// 转化为邻接表
for (int i = 0; i < MAXN; i++) {
for (int j = 0; j < MAXN; j++) {
if (matrix[i][j] == 1) {
adjList[i].push_back(j);
}
}
}
// 输出邻接表
for (int i = 0; i < MAXN; i++) {
cout << i << ": ";
for (int j = 0; j < adjList[i].size(); j++) {
cout << adjList[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果如下:
```
0: 1 2 3
1: 0 4 5
2: 0 5 6
3: 0 7
4: 1
5: 1 2
6: 2 8 9
7: 3 10
8: 6
9: 6
10: 7
```
阅读全文