数据结构用C语言代码实现:建立顶点集为字符集的无向图的领接矩阵存储并输出
时间: 2023-06-25 11:01:53 浏览: 117
数据结构C语言实现
以下是用C语言实现建立顶点集为字符集的无向图的领接矩阵存储并输出的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_VERTEX_NUM 20
typedef struct {
char vertex[MAX_VERTEX_NUM];
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vertex_num, edge_num;
} MGraph;
MGraph* createGraph(char* vertex, int vertex_num, int edge_num, char edges[][2]) {
MGraph* graph = (MGraph*)malloc(sizeof(MGraph));
if (graph == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
memset(graph->edge, 0, sizeof(graph->edge));
graph->vertex_num = vertex_num;
graph->edge_num = edge_num;
memcpy(graph->vertex, vertex, sizeof(char) * vertex_num);
for (int i = 0; i < edge_num; i++) {
int start = edges[i][0] - 'a';
int end = edges[i][1] - 'a';
graph->edge[start][end] = 1;
graph->edge[end][start] = 1;
}
return graph;
}
void printGraph(MGraph* graph) {
printf(" ");
for (int i = 0; i < graph->vertex_num; i++) {
printf("%c ", graph->vertex[i]);
}
printf("\n");
for (int i = 0; i < graph->vertex_num; i++) {
printf("%c ", graph->vertex[i]);
for (int j = 0; j < graph->vertex_num; j++) {
printf("%d ", graph->edge[i][j]);
}
printf("\n");
}
}
int main() {
char vertex[MAX_VERTEX_NUM] = {'a', 'b', 'c', 'd', 'e'};
char edges[][2] = {{'a', 'b'}, {'a', 'c'}, {'a', 'd'}, {'b', 'c'}, {'c', 'd'}, {'c', 'e'}, {'d', 'e'}};
int vertex_num = 5;
int edge_num = 7;
MGraph* graph = createGraph(vertex, vertex_num, edge_num, edges);
printGraph(graph);
return 0;
}
```
代码中,我们定义了一个结构体`MGraph`来表示图,其中包含顶点数组`vertex`、领接矩阵`edge`、顶点数`vertex_num`和边数`edge_num`。`createGraph`函数用于创建图,它接受顶点数组、顶点数、边数和边的数组作为参数,通过遍历边的数组来初始化领接矩阵。`printGraph`函数用于打印图,它先打印顶点数组,然后遍历领接矩阵,打印每个元素。最后在`main`函数中创建图并打印。
阅读全文