1、已知无向图的邻接矩阵,求无向图的邻接表。 (1)提示:无向图如下图(a)所示,已知邻接矩阵如图(b)所示,求对应的邻接表(c)。 (2)请定义void adjMatrix_2_adjList(int b[4][4], AdjList a)函数
时间: 2023-06-11 13:09:16 浏览: 58
(a) 无向图示意图:
```
1--2
/ |
3----4
```
(b) 邻接矩阵:
```
| 1 2 3 4
--|---------
1 | 0 1 1 0
2 | 1 0 1 1
3 | 1 1 0 1
4 | 0 1 1 0
```
(c) 对应的邻接表:
```
1 -> 2 -> 3
2 -> 1 -> 3 -> 4
3 -> 1 -> 2 -> 4
4 -> 2 -> 3
```
定义函数 `void adjMatrix_2_adjList(int b[4][4], AdjList a)`,其中 `b` 为输入的邻接矩阵,`a` 为输出的邻接表,函数实现如下:
```c++
struct Node {
int val;
Node* next;
Node(int v) : val(v), next(nullptr) {}
};
struct AdjList {
vector<Node*> list;
AdjList(int n) : list(n) {}
};
void adjMatrix_2_adjList(int b[4][4], AdjList a) {
int n = a.list.size();
// 构建每个顶点的链表
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (b[i][j] == 1) {
if (!a.list[i]) {
a.list[i] = new Node(j);
} else {
Node* cur = a.list[i];
while (cur->next) {
cur = cur->next;
}
cur->next = new Node(j);
}
}
}
}
}
```
上述函数先根据邻接表的长度 `n` 构建一个大小为 `n` 的 `AdjList` 结构体 `a`,然后对于每个顶点 `i`,遍历与其相邻的顶点 `j`,然后将 `j` 加入到 `i` 的链表中,最终得到邻接表 `a`。