-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprims.c
113 lines (100 loc) · 2.4 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
#include<stdio.h>
#include<stdlib.h>
int G[10][10],E[10][10];
int n;
void generate(int e)
{
int i,j,p,q,k=1,w;
while(k<=e)
{
printf("\nenter the connection ");
scanf("%d %d",&p,&q);
printf("\nenter its weight");
scanf("%d",&w);
G[p][q]=w;
G[q][p]=w;
k++;
}
}
void Prim()
{
int l1[n],l2[n],Vx[n-1],wt=0;
int st,i,j,k,b=0;
printf("enter the starting vertex");
scanf("%d",&st);
for(i=0;i<n;i++)
{
l1[i]=-1;
l2[i]=99;
}
for(i=0;i<n;i++)
{
if(i!=st)
Vx[b++]=i;
}
int lst=st;
for(k=0;k<n-1;k++)
{
for(j=0;j<b;j++)
{
int p=Vx[j];
if(G[lst][p]!=9999)
{
l1[p]=lst;
l2[p]=G[lst][p];
}
}
int min=l2[lst],pos;
for(i=0;i<n;i++)
{
if(min>l2[i])
{
min=l2[i];
pos=i;
}
}
wt=wt+min;
l2[pos]=99;
E[lst][pos]=1;
E[pos][lst]=1;
lst=pos;
int pp;
for(i=0;i<b;i++)
if(Vx[i]==pos)
pp=i;
for(i=pp;i<b-1;i++)
Vx[i]=Vx[i+1];
b--;
}
printf("\n weight=%d",wt);
}
void main()
{
int i,j,e;
printf("enter no of vertices");
scanf("%d",&n);
printf("enter no of edges");
scanf("%d",&e);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
G[i][j]=9999;
E[i][j]=0;
}
}
generate(e);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d \t",G[i][j]);
printf("\n");
}
Prim();
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d \t",E[i][j]);
printf("\n");
}
}