prime算法求最小生成树C语言代码
时间: 2023-03-27 21:01:03 浏览: 124
以下是 prime 算法求最小生成树的 C 语言代码:
```c
#include <stdio.h>
#include <limits.h>
#define V 5 // 图的顶点数
int minKey(int key[], int mstSet[]) {
int min = INT_MAX, min_index;
for (int v = ; v < V; v++) {
if (mstSet[v] == && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
void printMST(int parent[], int graph[V][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]]);
}
}
void primMST(int graph[V][V]) {
int parent[V];
int key[V];
int mstSet[V];
for (int i = ; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = ;
}
key[] = ;
parent[] = -1;
for (int count = ; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = 1;
for (int v = ; v < V; v++) {
if (graph[u][v] && mstSet[v] == && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printMST(parent, graph);
}
int main() {
int graph[V][V] = {
{ , 2, , 6, },
{ 2, , 3, 8, 5 },
{ , 3, , , 7 },
{ 6, 8, , , 9 },
{ , 5, 7, 9, }
};
primMST(graph);
return ;
}
```
希望能对你有所帮助。
阅读全文