用c写出需要输入点坐标的prim算法
时间: 2024-05-02 09:16:13 浏览: 90
prim算法(C语言编写)
5星 · 资源好评率100%
以下是用 C 语言实现的 Prim 算法,需要输入点坐标:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_VERTICES 100
#define INF 1000000
struct Point {
int x;
int y;
};
struct Graph {
int num_vertices;
struct Point vertices[MAX_VERTICES];
int adj_matrix[MAX_VERTICES][MAX_VERTICES];
};
int get_distance(struct Point p1, struct Point p2) {
return (int)(sqrt(pow(p1.x - p2.x, 2) + pow(p1.y - p2.y, 2)));
}
struct Graph* create_graph(int num_vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->num_vertices = num_vertices;
for (int i = 0; i < num_vertices; i++) {
scanf("%d %d", &(graph->vertices[i].x), &(graph->vertices[i].y));
for (int j = 0; j < num_vertices; j++) {
if (i == j) {
graph->adj_matrix[i][j] = 0;
} else {
graph->adj_matrix[i][j] = INF;
}
}
}
return graph;
}
void add_edge(struct Graph* graph, int src, int dest, int weight) {
graph->adj_matrix[src][dest] = weight;
graph->adj_matrix[dest][src] = weight;
}
void prim(struct Graph* graph) {
int visited[MAX_VERTICES], distance[MAX_VERTICES], parent[MAX_VERTICES];
for (int i = 0; i < graph->num_vertices; i++) {
visited[i] = 0;
distance[i] = INF;
}
distance[0] = 0;
parent[0] = -1;
for (int i = 0; i < graph->num_vertices - 1; i++) {
int u, min_distance = INF;
for (int j = 0; j < graph->num_vertices; j++) {
if (!visited[j] && distance[j] < min_distance) {
u = j;
min_distance = distance[j];
}
}
visited[u] = 1;
for (int v = 0; v < graph->num_vertices; v++) {
if (graph->adj_matrix[u][v] != 0 && !visited[v] && graph->adj_matrix[u][v] < distance[v]) {
parent[v] = u;
distance[v] = graph->adj_matrix[u][v];
}
}
}
printf("Edges of the minimum spanning tree:\n");
for (int i = 1; i < graph->num_vertices; i++) {
printf("%d - %d\n", parent[i], i);
}
}
int main() {
int num_vertices;
printf("Enter the number of vertices: ");
scanf("%d", &num_vertices);
struct Graph* graph = create_graph(num_vertices);
for (int i = 0; i < graph->num_vertices; i++) {
for (int j = i + 1; j < graph->num_vertices; j++) {
int weight = get_distance(graph->vertices[i], graph->vertices[j]);
add_edge(graph, i, j, weight);
}
}
prim(graph);
free(graph);
return 0;
}
```
该程序将首先要求用户输入点的数量,然后要求用户输入每个点的坐标,输入完成后程序将计算每对点之间的距离并构建带权完全图,然后运行 Prim 算法来计算最小生成树并输出。
阅读全文