c语言实现prim算法与克鲁斯卡尔算法
时间: 2024-12-30 07:24:38 浏览: 14
### C语言实现Prim算法和Kruskal算法
#### 1. Prim算法的C语言实现
Prim算法用于寻找加权连通图中的最小生成树。该算法通过逐步扩展一棵树来进行工作,每次迭代都会找到一条权重最小的新边并将其加入到现有的树中。
```c
#include <stdio.h>
#include <limits.h>
#define V 10
int minKey(int key[], int mstSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; 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 = 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] && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, graph);
}
```
这段代码展示了如何利用数组`key[]`保存最短路径估计值以及使用布尔型数组`mstSet[]`跟踪节点是否已处理完毕[^1]。
#### 2. Kruskal算法的C语言实现
Kruskal算法同样用来构建最小生成树,不过它采取了一种不同的策略——按照边的权重升序排列,并依次尝试添加每条边至最终的结果集中,前提是这样做不会形成任何循环。
为了有效地管理这些集合之间的关系,在此引入了不相交集数据结构(Disjoint Set Data Structure),也称为Union-Find结构体。
```c
#include <stdio.h>
#include <stdlib.h>
struct Edge {
int src, dest, weight;
};
struct Graph {
int V, E;
struct Edge* edge;
};
struct subset {
int parent;
int rank;
};
int find(struct subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
void Union(struct subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
int myComp(const void *a, const void *b) {
struct Edge *a1 = (struct Edge *) a;
struct Edge *b1 = (struct Edge *) b;
return a1->weight > b1->weight;
}
void kruskalMST(struct Graph* graph) {
int V = graph->V;
struct Edge result[V];
int e = 0;
int i = 0;
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
struct subset *subsets =
(struct subset*) malloc(V * sizeof(struct subset));
for (int v = 0; v < V; ++v) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
while (e < V - 1 && i < graph->E) {
struct Edge next_edge = graph->edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
printf("Following are the edges in the constructed MST\n");
for (i = 0; i < e; ++i)
printf("%d -- %d == %d\n", result[i].src,
result[i].dest, result[i].weight);
return;
}
```
上述程序实现了Kruskal算法的核心逻辑,包括快速排序函数`qsort()`的应用、查找根结点的方法`find()`以及合并子集的操作`Union()`. 此外还定义了一个辅助性的比较器`myComp()`以便于对所有的边按其权重进行排序[^2].
阅读全文