用prim算法求给定无向连通网的最小生成树,输入无向连通网的顶点数,起始顶点及无向连通网各边的权值,输出边和权值,C语言
时间: 2023-07-15 09:11:23 浏览: 113
以下是用Prim算法求给定无向连通网的最小生成树的C语言代码:
```c
#include <stdio.h>
#include <limits.h>
#define MAX_VERTICES 100
int graph[MAX_VERTICES][MAX_VERTICES];
int parent[MAX_VERTICES];
int key[MAX_VERTICES];
int visited[MAX_VERTICES];
int minKey(int n) {
int min = INT_MAX, min_index;
for (int v = 0; v < n; v++) {
if (visited[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
void primMST(int n, int start) {
for (int i = 0; i < n; i++) {
key[i] = INT_MAX;
visited[i] = 0;
}
key[start] = 0;
parent[start] = -1;
for (int count = 0; count < n - 1; count++) {
int u = minKey(n);
visited[u] = 1;
for (int v = 0; v < n; v++) {
if (graph[u][v] && visited[v] == 0 && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
printf("Edges \tWeight\n");
for (int i = 1; i < n; i++) {
printf("%d - %d \t%d\n", parent[i], i, graph[i][parent[i]]);
}
}
int main() {
int n, start;
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the start vertex: ");
scanf("%d", &start);
printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &graph[i][j]);
}
}
primMST(n, start);
return 0;
}
```
其中,`graph` 为邻接矩阵,`parent` 为每个顶点在最小生成树中的父节点,`key` 为每个顶点到最小生成树的距离,`visited` 用于标记顶点是否已经被访问。`minKey` 函数用于寻找未访问顶点中 key 值最小的顶点,`primMST` 函数用于实现 Prim 算法求解最小生成树,最后输出每条边和权值。
阅读全文