用kruskal算法求最小生成树 C语言
时间: 2023-11-12 11:56:05 浏览: 71
Kruskal算法是一种用于求解最小生成树的贪心算法。下面是使用C语言实现Kruskal算法的步骤:
1. 定义结构体来表示边:
```c
struct Edge {
int src, dest, weight;
};
```
2. 定义函数来比较两个边的权重:
```c
int compare(const void* a, const void* b) {
struct Edge* edge1 = (struct Edge*)a;
struct Edge* edge2 = (struct Edge*)b;
return edge1->weight - edge2->weight;
}
```
3. 定义函数来查找一个顶点的父节点:
```c
int find(int parent[], int i) {
if (parent[i] == -1)
return i;
return find(parent, parent[i]);
}
```
4. 定义函数来合并两个顶点的集合:
```c
void unionSets(int parent[], int x, int y) {
int rootX = find(parent, x);
int rootY = find(parent, y);
parent[rootX] = rootY;
}
```
5. 定义函数来应用Kruskal算法求最小生成树:
```c
void kruskalMST(struct Edge edges[], int V, int E) {
// 按权重对边进行排序
qsort(edges, E, sizeof(edges[0]), compare);
struct Edge result[V];
int parent[V];
memset(parent, -1, sizeof(parent));
int i = 0, j = 0;
while (i < V - 1 && j < E) {
struct Edge nextEdge = edges[j++];
int x = find(parent, nextEdge.src);
int y = find(parent, nextEdge.dest);
if (x != y) {
result[i++] = nextEdge;
unionSets(parent, x, y);
}
}
printf("最小生成树的边:\n");
for (i = 0; i < V - 1; i++) {
printf("%d - %d, 权重: %d\n", result[i].src, result[i].dest, result[i].weight);
}
}
```
6. 在主函数中调用Kruskal算法函数,并传入边的信息:
```c
int main() {
int V = 4; // 顶点数
int E = 5; // 边数
struct Edge edges[] = { {0, 1, 10}, {0, 2, 6}, {0, 3, 5}, {1, 3, 15}, {2, 3, 4} };
kruskalMST(edges, V, E);
return 0;
}
```
以上就是使用C语言实现Kruskal算法求解最小生成树的代码。希望对你有帮助!