-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprims.c
110 lines (90 loc) · 1.7 KB
/
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/******************************************
*
* Prims algorithm
*
* Harsimran Singh
*
* finds the cost of min. spanning tree
* using prims algorithm
*
******************************************/
#include<stdio.h>
int main()
{
int cost[10][10];
int n;
int i, j;
printf("enter the num of edges: ");
scanf("%d", &n);
for (i = 0 ; i < n; i++)
{
for (j = 0 ; j < n; j++)
{
scanf("%d", &cost[i][j]);
}
}
int near[1000];
int u = 0, v = 0, min = 9999999;
//find the minimum edges
for (i = 0; i < n; i++)
{
for (j = 0 ; j < n; j++)
{
if (cost[i][j] < min)
{
min = cost[i][j];
u = i;
v = j;
}
}
}
printf("found min edge : %d %d and weight : %d\n", u, v, min);
int weight = min;
//initializing the near of other elements
for (i = 0; i < n; i++)
{
if (cost[i][u] < cost[i][v])
{
near[i] = u;
}
else
{
near[i] = v;
}
}
near[u] = -1; near[v] = -1;
//printf("");
for (j = 1; j < n-1; j++)
{
//picking the minimum
int min = 99999999, minvertex;
for (i = 0 ; i < n; i++)
{
if (near[i] != -1)
{
if (cost[i][near[i]] < min)
{
min = cost[i][near[i]];
minvertex = i;
}
}
}
printf("min vertex: %d from %d and edge : %d\n", minvertex,near[minvertex], min);
near[minvertex] = -1;
weight += min;
//check if adding the vertex causes any change
for (i = 0; i < n; i++)
{
if (near[i] != -1)
{
if (cost[i][minvertex] < cost[i][near[i]])
{
near[i] = minvertex;
}
}
}
}
printf("%d\n", weight);
return 0;
}