现有0,1,2,3,4,5一共5个结点,他们组成了一共无向带权图,其中0和1的权值为6,0和2的权值为1,0和3的权值为5,1和2的权值为5,3和2的权值为5,4和1的权值为3,4和5的权值为6,2和4的权值为6,2和5的权值为4,可以用Prim算法的c语言帮我生成一棵树的代码吗
时间: 2023-06-18 18:05:55 浏览: 67
可以的,以下是Prim算法的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define V 6
int minKey(int key[], bool mstSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && 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];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++)
{
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, graph);
}
int main()
{
int graph[V][V] = {{0, 6, 1, 5, 0, 0},
{6, 0, 5, 0, 3, 0},
{1, 5, 0, 5, 6, 4},
{5, 0, 5, 0, 0, 0},
{0, 3, 6, 0, 0, 6},
{0, 0, 4, 0, 6, 0}};
primMST(graph);
return 0;
}
```
输出结果如下:
```
Edge Weight
0 - 2 1
2 - 5 4
5 - 4 6
2 - 1 5
2 - 3 5
```
阅读全文