c语言用文件操作实现有向图网的邻接矩阵存储
时间: 2023-09-05 20:13:59 浏览: 101
dg.zip_dirtddf_图 数据结构_数据结构 图_数据结构 C语言_有向图
实现有向图网的邻接矩阵存储可以分为以下几个步骤:
1. 定义邻接矩阵的数据结构,包括节点个数、边数、邻接矩阵等。
```
#define MAX_VERTEX_NUM 20 // 最大节点数
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 节点数组
int arc[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
int vertex_num; // 节点个数
int arc_num; // 边数
} Graph;
```
2. 编写函数读取图的信息并创建邻接矩阵。这里可以采用文件操作,将图的信息存储在文件中,然后读取文件内容来创建邻接矩阵。
```
void create_graph(Graph* graph, char* filename) {
FILE* fp = fopen(filename, "r");
fscanf(fp, "%d %d", &(graph->vertex_num), &(graph->arc_num)); // 读取节点个数和边数
for (int i = 0; i < graph->vertex_num; i++) {
fscanf(fp, "%d", &(graph->vertex[i])); // 读取节点数组
}
memset(graph->arc, 0, sizeof(graph->arc)); // 初始化邻接矩阵
int start, end, weight;
for (int i = 0; i < graph->arc_num; i++) {
fscanf(fp, "%d %d %d", &start, &end, &weight); // 读取边信息
graph->arc[start][end] = weight; // 更新邻接矩阵
}
fclose(fp);
}
```
3. 编写函数输出邻接矩阵。这里可以将邻接矩阵输出到文件中,也可以直接在控制台输出。
```
void print_graph(Graph graph) {
printf("Vertexes:\n");
for (int i = 0; i < graph.vertex_num; i++) {
printf("%d ", graph.vertex[i]);
}
printf("\n");
printf("Adjacency matrix:\n");
for (int i = 0; i < graph.vertex_num; i++) {
for (int j = 0; j < graph.vertex_num; j++) {
printf("%d ", graph.arc[i][j]);
}
printf("\n");
}
}
```
完整代码如下:
```
#include <stdio.h>
#include <string.h>
#define MAX_VERTEX_NUM 20 // 最大节点数
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 节点数组
int arc[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
int vertex_num; // 节点个数
int arc_num; // 边数
} Graph;
void create_graph(Graph* graph, char* filename) {
FILE* fp = fopen(filename, "r");
fscanf(fp, "%d %d", &(graph->vertex_num), &(graph->arc_num)); // 读取节点个数和边数
for (int i = 0; i < graph->vertex_num; i++) {
fscanf(fp, "%d", &(graph->vertex[i])); // 读取节点数组
}
memset(graph->arc, 0, sizeof(graph->arc)); // 初始化邻接矩阵
int start, end, weight;
for (int i = 0; i < graph->arc_num; i++) {
fscanf(fp, "%d %d %d", &start, &end, &weight); // 读取边信息
graph->arc[start][end] = weight; // 更新邻接矩阵
}
fclose(fp);
}
void print_graph(Graph graph) {
printf("Vertexes:\n");
for (int i = 0; i < graph.vertex_num; i++) {
printf("%d ", graph.vertex[i]);
}
printf("\n");
printf("Adjacency matrix:\n");
for (int i = 0; i < graph.vertex_num; i++) {
for (int j = 0; j < graph.vertex_num; j++) {
printf("%d ", graph.arc[i][j]);
}
printf("\n");
}
}
int main() {
Graph graph;
char filename[] = "graph.txt";
create_graph(&graph, filename);
print_graph(graph);
return 0;
}
```
阅读全文