请用c语言编程实现Prim算法
时间: 2023-09-28 18:11:03 浏览: 92
以下是C语言实现Prim算法的示例代码:
```c
#include <stdio.h>
#include <stdbool.h>
#define INF 999999
int main() {
int graph[10][10], visited[10], dist[10], parent[10];
int vertices, edges, i, j, min_dist, min_vertex, total_weight = 0;
// input number of vertices and edges
printf("Enter number of vertices: ");
scanf("%d", &vertices);
printf("Enter number of edges: ");
scanf("%d", &edges);
// initialize graph with INF
for(i = 0; i < vertices; i++) {
for(j = 0; j < vertices; j++) {
graph[i][j] = INF;
}
}
// input edges and weights
for(i = 0; i < edges; i++) {
int u, v, w;
printf("Enter edge %d and weight: ", i + 1);
scanf("%d %d %d", &u, &v, &w);
graph[u][v] = w;
graph[v][u] = w;
}
// initialize visited, dist, parent arrays
for(i = 0; i < vertices; i++) {
visited[i] = false;
dist[i] = INF;
parent[i] = -1;
}
// start from vertex 0
dist[0] = 0;
// loop over all vertices
for(i = 0; i < vertices; i++) {
// find unvisited vertex with minimum distance
min_dist = INF;
for(j = 0; j < vertices; j++) {
if(!visited[j] && dist[j] < min_dist) {
min_dist = dist[j];
min_vertex = j;
}
}
// mark vertex as visited
visited[min_vertex] = true;
// update distances and parents of adjacent vertices
for(j = 0; j < vertices; j++) {
if(graph[min_vertex][j] != INF && !visited[j] && graph[min_vertex][j] < dist[j]) {
dist[j] = graph[min_vertex][j];
parent[j] = min_vertex;
}
}
}
// calculate total weight of MST
for(i = 0; i < vertices; i++) {
total_weight += dist[i];
}
// print MST edges and total weight
printf("MST Edges: \n");
for(i = 1; i < vertices; i++) {
printf("(%d, %d)\n", parent[i], i);
}
printf("Total weight of MST: %d", total_weight);
return 0;
}
```
该程序通过从第一个顶点开始,一步一步构建最小生成树。visited数组记录已经访问过的顶点,dist数组记录每个顶点到已访问顶点的最小距离,parent数组记录每个顶点在最小生成树中的父节点。程序输出最小生成树的边和总权值。
阅读全文