c语言 图的存储邻接矩阵,C语言 实现邻接矩阵存储图
时间: 2023-10-18 10:12:02 浏览: 34
C语言实现图的邻接矩阵存储操作
5星 · 资源好评率100%
好的,下面是 C 语言实现邻接矩阵存储图的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 20
typedef struct {
int vertex[MAX_VERTEX_NUM];
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
int vertexNum, edgeNum;
} Graph;
void createGraph(Graph *graph) {
printf("请输入图的顶点数和边数:\n");
scanf("%d %d", &(graph->vertexNum), &(graph->edgeNum));
printf("请输入图的顶点:\n");
for (int i = 0; i < graph->vertexNum; i++) {
scanf("%d", &(graph->vertex[i]));
}
for (int i = 0; i < graph->vertexNum; i++) {
for (int j = 0; j < graph->vertexNum; j++) {
graph->edge[i][j] = 0;
}
}
printf("请输入图的边的信息:\n");
for (int k = 0; k < graph->edgeNum; k++) {
int i, j;
scanf("%d %d", &i, &j);
graph->edge[i][j] = graph->edge[j][i] = 1;
}
}
void printGraph(Graph *graph) {
printf("图的顶点为:\n");
for (int i = 0; i < graph->vertexNum; i++) {
printf("%d ", graph->vertex[i]);
}
printf("\n");
printf("图的邻接矩阵为:\n");
for (int i = 0; i < graph->vertexNum; i++) {
for (int j = 0; j < graph->vertexNum; j++) {
printf("%d ", graph->edge[i][j]);
}
printf("\n");
}
}
int main() {
Graph graph;
createGraph(&graph);
printGraph(&graph);
return 0;
}
```
这个程序实现了创建一个无向图的邻接矩阵,并打印出来。其中,`Graph` 结构体表示一个图,包含 `vertex` 数组表示顶点,`edge` 数组表示边,`vertexNum` 表示顶点数,`edgeNum` 表示边数。在 `createGraph` 函数中,先输入顶点数和边数,然后分别输入顶点和边的信息,最后根据边的信息构建邻接矩阵。在 `printGraph` 函数中,先打印顶点,再打印邻接矩阵。
阅读全文