用c语言实现图示的存储,输出存储结构示意图
时间: 2024-02-24 19:59:39 浏览: 32
好的,以下是用C语言实现的图示存储的示例代码和存储结构示意图:
示例代码:
```c
#include <stdio.h>
#define MAX_VERTICES 10
typedef struct {
int visited;
int vertex;
} Vertex;
typedef struct {
Vertex vertices[MAX_VERTICES];
int edges[MAX_VERTICES][MAX_VERTICES];
int num_vertices;
} Graph;
void init_graph(Graph* graph, int num_vertices) {
graph->num_vertices = num_vertices;
for (int i = 0; i < num_vertices; i++) {
graph->vertices[i].visited = 0;
graph->vertices[i].vertex = i;
for (int j = 0; j < num_vertices; j++) {
graph->edges[i][j] = 0;
}
}
}
void add_edge(Graph* graph, int start_vertex, int end_vertex) {
graph->edges[start_vertex][end_vertex] = 1;
graph->edges[end_vertex][start_vertex] = 1;
}
void print_graph(Graph* graph) {
printf("Graph:\n");
for (int i = 0; i < graph->num_vertices; i++) {
printf("%d: ", graph->vertices[i].vertex);
for (int j = 0; j < graph->num_vertices; j++) {
if (graph->edges[i][j] == 1) {
printf("%d ", graph->vertices[j].vertex);
}
}
printf("\n");
}
}
int main() {
Graph graph;
init_graph(&graph, 4);
add_edge(&graph, 0, 1);
add_edge(&graph, 0, 2);
add_edge(&graph, 1, 2);
add_edge(&graph, 2, 3);
print_graph(&graph);
return 0;
}
```
存储结构示意图:
```
Graph:
0: 1 2
1: 0 2
2: 0 1 3
3: 2
```
其中,每个数字代表一个顶点,数字后面的空格后跟的数字代表与该顶点相连的其他顶点。例如,`0: 1 2`表示顶点0与顶点1、顶点2相连。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)