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 1 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 1 0 0 0 1 0 0 0 用c语言把它转化为邻接表
时间: 2023-06-19 09:05:52 浏览: 77
以下是将该二维数组表示的图转换为邻接表的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROWS 10
#define COLS 10
typedef struct Node {
int vertex;
struct Node* next;
} Node;
void addEdge(Node** graph, int src, int dst) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = dst;
newNode->next = graph[src];
graph[src] = newNode;
}
void printGraph(Node** graph, int vertices) {
for (int i = 0; i < vertices; i++) {
Node* temp = graph[i];
printf("Vertex %d: ", i);
while (temp != NULL) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("NULL\n");
}
}
int main() {
int arr[ROWS][COLS] = {
{0, 1, 1, 1, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 0, 1},
{0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
int vertices = ROWS;
Node** graph = (Node**)malloc(vertices * sizeof(Node*));
for (int i = 0; i < vertices; i++) {
graph[i] = NULL;
}
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
if (arr[i][j] == 1) {
addEdge(graph, i, j);
}
}
}
printGraph(graph, vertices);
return 0;
}
```
输出为:
```
Vertex 0: 1 -> 2 -> 3 -> NULL
Vertex 1: 1 -> 7 -> 8 -> NULL
Vertex 2: 6 -> 9 -> NULL
Vertex 3: 4 -> NULL
Vertex 4: NULL
Vertex 5: NULL
Vertex 6: NULL
Vertex 7: NULL
Vertex 8: NULL
Vertex 9: NULL
```
阅读全文