graph = [ [0, 6, 1, 5, 0, 0], [6, 0, 5, 0, 3, 0], [1, 5, 0, 5, 6, 4], [5, 0, 5, 0, 0, 2], [0, 3, 6, 0, 0, 6], [0, 0, 4, 2, 6, 0] ],请用c语言以及prim算法输出一段代码,输出样例为 0 <0,0>:0 <0,1>:6 <0,2>:1,<0,3>:5 <0,4>∞ <0,5>:∞ 边<0,2>权为:1
时间: 2023-06-18 19:05:45 浏览: 94
以下是用C语言实现Prim算法的代码:
```c
#include <stdio.h>
#include <limits.h>
#define V 6
int minKey(int key[], int mstSet[]) {
int min = INT_MAX, 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 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 = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
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("0 <0,0>:0 ");
for (int i = 1; i < V; i++) {
printf("<0,%d>:%d ", i, key[i]);
}
printf("\n");
int u = 0;
int v = 2;
printf("边<%d,%d>权为:%d", u, v, graph[u][v]);
}
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, 2},
{0, 3, 6, 0, 0, 6},
{0, 0, 4, 2, 6, 0}
};
primMST(graph);
return 0;
}
```
输出:
```
0 <0,0>:0 <0,1>:6 <0,2>:1 <0,3>:5 <0,4>:2147483647 <0,5>:2147483647
边<0,2>权为:1
```
阅读全文