1、Prim算法和Kruskal算法实现最小生成树。C语言
时间: 2024-06-03 10:03:09 浏览: 121
以下是Prim算法和Kruskal算法实现最小生成树的C语言代码:
1. Prim算法实现最小生成树
```c
#include <stdio.h>
#include <limits.h>
#define V 5 // 顶点数
int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (mstSet[v] == false && 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];
bool mstSet[V];
for (int i = 0; i < V; i++) {
key[i] = INT_MAX, mstSet[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++) {
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) {
parent[v] = u, key[v] = graph[u][v];
}
}
}
printMST(parent, graph);
}
```
2. Kruskal算法实现最小生成树
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define V 5 // 顶点数
#define E 7 // 边数
struct Edge {
int src, dest, weight;
};
struct Graph {
int V, E;
struct Edge* edge;};
struct Graph* createGraph(int V, int E) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->E = E;
graph->edge = (struct Edge*)malloc(graph->E * sizeof(struct Edge));
return graph;
}
int find(int parent[], int i) {
if (parent[i] == -1) {
return i;
}
return find(parent, parent[i]);
}
void Union(int parent[], int x, int y) {
int xset = find(parent, x);
int yset = find(parent, y);
parent[xset] = yset;
}
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* parent = (int*)malloc(graph->V * sizeof(int));
memset(parent, -1, sizeof(int) * graph->V);
qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp);
struct Edge result[graph->V];
int e = 0, i = 0;
while (e < graph->V - 1 && i < graph->E) {
struct Edge next_edge = graph->edge[i++];
int x = find(parent, next_edge.src);
int y = find(parent, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(parent, 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;
}
```
阅读全文