-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathprims.c
98 lines (93 loc) · 1.53 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
#include <stdio.h>
# define I 100000
static int n;
void prim(int cost[n+1][n+1],int t[][n-1])
{
int near[n+1];
int i,j,u,v,min,k;
for(i=0;i<=n;i++)
{
near[i]=I;
}
min=I;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
u=i;
v=j;
}
}
}
t[0][0]=u;
t[1][0]=v;
near[u]=near[v]=0;
for(i=1;i<=7;i++)
{
if(near[i]!=0)
{
if(cost[i][v]>cost[i][u])
near[i]=u;
else
near[i]=v;
}
}
for(i=1;i<=n-2;i++)
{
min=I;
for(j=1;j<=n;j++)
{
if(near[j]!=0)
{
if(cost[j][near[j]]<min)
{
min=cost[j][near[j]];
k=j;
}
}
}
t[0][i]=near[k];
t[1][i]=k;
near[k]=0;
for(j=1;j<=n;j++)
{
if(near[j]!=0)
{
if(cost[j][k]<cost[j][near[j]])
near[j]=k;
}
}
}
}
int main()
{
printf("No. of vertex/Nodes in a graph :");
scanf("%d",&n);
int cost[n+1][n+1];
int t[2][n-1];
int i,j,sum=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("Enter the weight 0f path from v[%d] to v[%d] or 0 if no path exists:",i,j);
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
{
cost[i][j]=I;
}
}
}
prim(cost,t);
printf("Minimum cost path is");
for(i=0;i<n-1;i++)
{
printf("\n v[%d] to v[%d]", t[0][i],t[1][i]);
sum=sum +cost[t[0][i]][t[1][i]];
}
printf("\n \nMinimum Cost of the spanning tree is %d",sum);
return 0;
}