forked from AtitBimali/DAA-labs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
17_prims.c
87 lines (66 loc) · 1.83 KB
/
17_prims.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdlib.h>
#define infinity 9999
#define MAX 20
int G[MAX][MAX], spanning[MAX][MAX], n;
int prims();
int main() {
int i, j, total_cost;
printf("Enter no. of vertices:");
scanf("%d", &n);
printf("\nEnter the adjacency matrix:\n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &G[i][j]);
total_cost = prims();
printf("\nSpanning tree matrix:\n");
for (i = 0; i < n; i++) {
printf("\n");
for (j = 0; j < n; j++)
printf("%d\t", spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree = %d", total_cost);
return 0;
}
int prims() {
int cost[MAX][MAX];
int u, v, min_distance, distance[MAX], from[MAX];
int visited[MAX], no_of_edges, i, min_cost, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
if (G[i][j] == 0)
cost[i][j] = infinity;
else
cost[i][j] = G[i][j];
spanning[i][j] = 0;
}
distance[0] = 0;
visited[0] = 1;
for (i = 1; i < n; i++) {
distance[i] = cost[0][i];
from[i] = 0;
visited[i] = 0;
}
min_cost = 0;
no_of_edges = n - 1;
while (no_of_edges > 0) {
min_distance = infinity;
for (i = 1; i < n; i++)
if (visited[i] == 0 && distance[i] < min_distance) {
v = i;
min_distance = distance[i];
}
u = from[v];
spanning[u][v] = distance[v];
spanning[v][u] = distance[v];
no_of_edges--;
visited[v] = 1;
for (i = 1; i < n; i++)
if (visited[i] == 0 && cost[i][v] < distance[i]) {
distance[i] = cost[i][v];
from[i] = v;
}
min_cost = min_cost + cost[u][v];
}
return (min_cost);
}