c语言实现图的邻接矩阵储存结构
时间: 2023-09-05 11:15:08 浏览: 58
实现图的邻接矩阵储存结构需要以下步骤:
1. 定义一个结构体来表示图,包含图的顶点数和邻接矩阵。
```
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 存储顶点信息
int edges[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
int vertex_num, edge_num; // 顶点数和边数
} Graph;
```
2. 初始化图的结构体。
```
void init_graph(Graph *graph, int vertex_num) {
graph->vertex_num = vertex_num;
graph->edge_num = 0;
// 初始化邻接矩阵
for (int i = 0; i < graph->vertex_num; i++) {
for (int j = 0; j < graph->vertex_num; j++) {
graph->edges[i][j] = 0;
}
}
}
```
3. 添加边。
```
void add_edge(Graph *graph, int start, int end) {
graph->edges[start][end] = 1;
graph->edges[end][start] = 1;
graph->edge_num++;
}
```
4. 打印邻接矩阵。
```
void print_graph(Graph *graph) {
printf("邻接矩阵:\n");
for (int i = 0; i < graph->vertex_num; i++) {
for (int j = 0; j < graph->vertex_num; j++) {
printf("%d ", graph->edges[i][j]);
}
printf("\n");
}
}
```
完整代码如下:
```
#include <stdio.h>
#define MAX_VERTEX_NUM 100 // 最大顶点数
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 存储顶点信息
int edges[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
int vertex_num, edge_num; // 顶点数和边数
} Graph;
void init_graph(Graph *graph, int vertex_num) {
graph->vertex_num = vertex_num;
graph->edge_num = 0;
// 初始化邻接矩阵
for (int i = 0; i < graph->vertex_num; i++) {
for (int j = 0; j < graph->vertex_num; j++) {
graph->edges[i][j] = 0;
}
}
}
void add_edge(Graph *graph, int start, int end) {
graph->edges[start][end] = 1;
graph->edges[end][start] = 1;
graph->edge_num++;
}
void print_graph(Graph *graph) {
printf("邻接矩阵:\n");
for (int i = 0; i < graph->vertex_num; i++) {
for (int j = 0; j < graph->vertex_num; j++) {
printf("%d ", graph->edges[i][j]);
}
printf("\n");
}
}
int main() {
Graph graph;
init_graph(&graph, 5);
add_edge(&graph, 0, 1);
add_edge(&graph, 0, 2);
add_edge(&graph, 1, 3);
add_edge(&graph, 2, 4);
print_graph(&graph);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)