c语言实现普里姆算法求最小生成树,并给出测试数据
时间: 2023-07-15 22:12:59 浏览: 90
C实现最小生成树(普利姆算法)
5星 · 资源好评率100%
普里姆算法是一种用于求解带权无向连通图的最小生成树的算法。以下是使用 C 语言实现的普里姆算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100
#define INF INT_MAX
int minKey(int key[], int mstSet[], int V) {
int min = INF, min_index;
for (int v = 0; v < V; v++) {
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
void primMST(int graph[MAX_VERTICES][MAX_VERTICES], int V) {
int parent[MAX_VERTICES];
int key[MAX_VERTICES];
int mstSet[MAX_VERTICES];
for (int i = 0; i < V; i++) {
key[i] = INF;
mstSet[i] = 0;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet, V);
mstSet[u] = 1;
for (int v = 0; v < V; v++) {
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d\n", parent[i], i, graph[i][parent[i]]);
}
}
int main() {
int graph[MAX_VERTICES][MAX_VERTICES];
int V, E;
printf("Enter the number of vertices: ");
scanf("%d", &V);
printf("Enter the number of edges: ");
scanf("%d", &E);
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
graph[i][j] = 0;
}
}
printf("Enter the edges and their weights:\n");
for (int i = 0; i < E; i++) {
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
graph[u][v] = w;
graph[v][u] = w;
}
primMST(graph, V);
return 0;
}
```
下面是一个测试数据,表示一个带权无向连通图:
```
4
5
0 1 2
0 2 3
0 3 4
1 2 5
2 3 1
```
其中第一行表示图的顶点数,第二行表示边的数目,接下来的五行表示边和它们的权重。
阅读全文