写出从图的邻接表表示转换成邻接矩阵表示的算法, C语言写成过程形式。
时间: 2024-04-16 22:24:56 浏览: 16
以下是将图的邻接表表示转换为邻接矩阵表示的算法的C语言过程形式:
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_VERTICES 100
// 邻接表的链表节点
struct Node {
int vertex;
struct Node* next;
};
// 图的结构体
struct Graph {
struct Node* adjLists[MAX_VERTICES];
};
// 创建新节点
struct Node* createNode(int v) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// 创建图
struct Graph* createGraph() {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
for (int i = 0; i < MAX_VERTICES; i++) {
graph->adjLists[i] = NULL;
}
return graph;
}
// 添加边
void addEdge(struct Graph* graph, int src, int dest) {
// 添加 src -> dest 边
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
}
// 邻接表转邻接矩阵
void convertToMatrix(struct Graph* graph, int matrix[MAX_VERTICES][MAX_VERTICES]) {
for (int i = 0; i < MAX_VERTICES; i++) {
for (int j = 0; j < MAX_VERTICES; j++) {
matrix[i][j] = 0;
}
}
for (int i = 0; i < MAX_VERTICES; i++) {
struct Node* node = graph->adjLists[i];
while (node != NULL) {
matrix[i][node->vertex] = 1;
node = node->next;
}
}
}
// 打印邻接矩阵
void printMatrix(int matrix[MAX_VERTICES][MAX_VERTICES], int numVertices) {
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
struct Graph* graph = createGraph();
int numVertices, numEdges;
// 输入顶点数和边数
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);
printf("Enter the number of edges: ");
scanf("%d", &numEdges);
// 输入边信息
for (int i = 0; i < numEdges; i++) {
int src, dest;
printf("Enter edge %d (source destination): ", i + 1);
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
}
// 创建邻接矩阵
int matrix[MAX_VERTICES][MAX_VERTICES];
convertToMatrix(graph, matrix);
// 打印邻接矩阵
printf("Adjacency Matrix:\n");
printMatrix(matrix, numVertices);
return 0;
}
```
在上述代码中,我们首先定义了邻接表的链表节点结构 `Node` 和图的结构体 `Graph`。然后,我们实现了创建新节点、创建图、添加边、邻接表转邻接矩阵和打印邻接矩阵的函数。在 `main` 函数中,我们先输入顶点数和边数,然后输入边的信息并使用邻接表表示图。接下来,我们调用 `convertToMatrix` 函数将邻接表转换为邻接矩阵,并调用 `printMatrix` 函数打印出邻接矩阵。
注意:上述代码仅为示例,实际使用时需要根据实际情况进行修改。