帮我用C语言写一个数据结构图代码,要求是1. 选择邻接矩阵或邻接表其中一种对图进行存储; 2. 实现图的广度优先和深度优先两种遍历方法; 3. 实现图的最小生成树算法,Prim或kruskal算法二者均需实现
时间: 2024-03-25 15:39:50 浏览: 174
建立图的邻接矩阵或邻接表存储并在此基础上实现图的深度优先遍历和广度优先遍历.doc
5星 · 资源好评率100%
好的,以下是一个基于邻接矩阵的数据结构图代码,包含了广度优先、深度优先遍历和Prim算法的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTEX_NUM 20 // 最大顶点数
#define INF 1000000 // 无穷大
// 边结构体
typedef struct {
int weight; // 权值
int start; // 起点
int end; // 终点
} Edge;
// 图结构体
typedef struct {
int vertex[MAX_VERTEX_NUM]; // 顶点数组
int edge[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; // 邻接矩阵
int vertex_num; // 顶点数
int edge_num; // 边数
} Graph;
// 用邻接矩阵存储图
void create_graph(Graph *g) {
printf("请输入顶点数和边数:");
scanf("%d %d", &g->vertex_num, &g->edge_num);
// 初始化邻接矩阵
for (int i = 0; i < g->vertex_num; i++) {
for (int j = 0; j < g->vertex_num; j++) {
if (i == j) {
g->edge[i][j] = 0;
} else {
g->edge[i][j] = INF;
}
}
}
// 输入顶点
printf("请输入 %d 个顶点:", g->vertex_num);
for (int i = 0; i < g->vertex_num; i++) {
scanf("%d", &g->vertex[i]);
}
// 输入边
int start, end, weight;
printf("请输入每条边的起点、终点和权值:\n");
for (int i = 0; i < g->edge_num; i++) {
scanf("%d %d %d", &start, &end, &weight);
g->edge[start][end] = weight;
g->edge[end][start] = weight; // 无向图,需要对称存储
}
}
// 深度优先遍历
void dfs(Graph g, bool *visited, int vertex) {
visited[vertex] = true;
printf("%d ", g.vertex[vertex]);
for (int i = 0; i < g.vertex_num; i++) {
if (g.edge[vertex][i] != INF && !visited[i]) {
dfs(g, visited, i);
}
}
}
// 广度优先遍历
void bfs(Graph g, bool *visited, int vertex) {
int queue[MAX_VERTEX_NUM], front = 0, rear = 0;
visited[vertex] = true;
printf("%d ", g.vertex[vertex]);
queue[rear++] = vertex;
while (front < rear) {
int v = queue[front++];
for (int i = 0; i < g.vertex_num; i++) {
if (g.edge[v][i] != INF && !visited[i]) {
visited[i] = true;
printf("%d ", g.vertex[i]);
queue[rear++] = i;
}
}
}
}
// Prim算法求最小生成树
void prim(Graph g) {
int lowcost[MAX_VERTEX_NUM], closest[MAX_VERTEX_NUM];
bool visited[MAX_VERTEX_NUM] = {false};
for (int i = 1; i < g.vertex_num; i++) {
lowcost[i] = g.edge[0][i];
closest[i] = 0;
}
visited[0] = true;
printf("生成树的边为:\n");
for (int i = 1; i < g.vertex_num; i++) {
int min_cost = INF, min_vertex = -1;
for (int j = 1; j < g.vertex_num; j++) {
if (!visited[j] && lowcost[j] < min_cost) {
min_cost = lowcost[j];
min_vertex = j;
}
}
if (min_vertex != -1) {
printf("(%d,%d) ", g.vertex[closest[min_vertex]], g.vertex[min_vertex]);
visited[min_vertex] = true;
for (int j = 1; j < g.vertex_num; j++) {
if (!visited[j] && g.edge[min_vertex][j] < lowcost[j]) {
lowcost[j] = g.edge[min_vertex][j];
closest[j] = min_vertex;
}
}
}
}
}
int main() {
Graph g;
create_graph(&g);
bool visited[MAX_VERTEX_NUM] = {false};
printf("深度优先遍历结果为:");
dfs(g, visited, 0);
printf("\n");
for (int i = 0; i < g.vertex_num; i++) {
visited[i] = false;
}
printf("广度优先遍历结果为:");
bfs(g, visited, 0);
printf("\n");
prim(g);
return 0;
}
```
阅读全文