用prime算法求无向连通网的最小生成树,第一行输入顶点数,第二行为起始顶点,接着输入各边,C语言
时间: 2024-05-13 08:17:28 浏览: 65
以下是用prime算法求无向连通网的最小生成树的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 1000
typedef struct {
int weight;
int visited;
} Edge;
typedef struct {
Edge edges[MAX_VERTICES][MAX_VERTICES];
int num_vertices;
} Graph;
int get_min_edge(Graph* graph, int* distances) {
int min_edge = -1;
int min_distance = INT_MAX;
for (int i = 0; i < graph->num_vertices; i++) {
if (!graph->edges[i][i].visited && distances[i] < min_distance) {
min_edge = i;
min_distance = distances[i];
}
}
return min_edge;
}
void print_mst(Graph* graph, int* parents) {
printf("Minimum Spanning Tree:\n");
for (int i = 1; i < graph->num_vertices; i++) {
printf("(%d, %d) - %d\n", parents[i], i, graph->edges[i][parents[i]].weight);
}
}
void prim(Graph* graph, int start_vertex) {
int distances[MAX_VERTICES];
int parents[MAX_VERTICES];
for (int i = 0; i < graph->num_vertices; i++) {
distances[i] = INT_MAX;
parents[i] = -1;
}
distances[start_vertex] = 0;
for (int i = 0; i < graph->num_vertices; i++) {
int current_vertex = get_min_edge(graph, distances);
if (current_vertex == -1) {
break;
}
graph->edges[current_vertex][current_vertex].visited = 1;
for (int j = 0; j < graph->num_vertices; j++) {
if (graph->edges[current_vertex][j].weight > 0 && !graph->edges[j][j].visited && graph->edges[current_vertex][j].weight < distances[j]) {
distances[j] = graph->edges[current_vertex][j].weight;
parents[j] = current_vertex;
}
}
}
print_mst(graph, parents);
}
int main() {
Graph graph;
scanf("%d", &graph.num_vertices);
int start_vertex;
scanf("%d", &start_vertex);
for (int i = 0; i < graph.num_vertices; i++) {
for (int j = 0; j < graph.num_vertices; j++) {
graph.edges[i][j].weight = 0;
graph.edges[i][j].visited = 0;
}
}
int num_edges;
scanf("%d", &num_edges);
for (int i = 0; i < num_edges; i++) {
int vertex1, vertex2, weight;
scanf("%d %d %d", &vertex1, &vertex2, &weight);
graph.edges[vertex1][vertex2].weight = weight;
graph.edges[vertex2][vertex1].weight = weight;
}
prim(&graph, start_vertex);
return 0;
}
```
主要思路是使用一个一维数组`distances`来存储每个顶点到最小生成树的距离,然后每次选择距离最小的未访问过的顶点加入最小生成树,并更新`distances`数组。具体实现可以参考上述代码。
阅读全文