普利姆算法c语言实现完整代码
时间: 2023-10-30 09:08:05 浏览: 122
以下是普利姆算法的C语言实现完整代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAXV 1000
#define INF INT_MAX
typedef struct {
int n;
int edges[MAXV][MAXV];
} MatGraph;
void Prim(MatGraph g, int v) {
int lowcost[MAXV];
int closest[MAXV];
int i, j, k, mindist;
for (i = 0; i < g.n; i++) {
lowcost[i] = g.edges[v][i];
closest[i] = v;
}
for (i = 1; i < g.n; i++) {
mindist = INF;
for (j = 0; j < g.n; j++) {
if (lowcost[j] != 0 && lowcost[j] < mindist) {
mindist = lowcost[j];
k = j;
}
}
printf("(%d, %d) ", closest[k], k);
lowcost[k] = 0;
for (j = 0; j < g.n; j++) {
if (lowcost[j] != 0 && g.edges[k][j] < lowcost[j]) {
lowcost[j] = g.edges[k][j];
closest[j] = k;
}
}
}
}
int main() {
MatGraph g;
int i, j, n, m, u, v, w;
printf("请输入顶点数和边数:");
scanf("%d%d", &n, &m);
g.n = n;
for (i = 0; i < g.n; i++) {
for (j = 0; j < g.n; j++) {
g.edges[i][j] = INF;
}
}
printf("请输入每条边的起点、终点和权值:\n");
for (i = 0; i < m; i++) {
scanf("%d%d%d", &u, &v, &w);
g.edges[u][v] = w;
g.edges[v][u] = w;
}
printf("最小生成树的边为:\n");
Prim(g, 0);
return 0;
}
```
阅读全文