You are on page 1of 3

****program for prim's algorithm **** #include<stdio.h> #include<conio.h> #include<stdlib.

h> # d e f i n e s i z e 8 int cost[size][size]={0},n=0; void get_mat() { int i,j,v1,v2,wt; for(i=0;i<=size;i++) for(j=0;j<=size;j++) cost[i][j]=1000; printf("\nEnter the no. of vertices:"); scanf("%d",&n); do { printf("\nEnter the edge & their weight(v1 v2,wt):"); scanf("%d%d%d",&v1,&v2,&wt); cost[v1][v2]=cost[v2][v1]=wt; printf("\nContinue:"); fflush(stdin); }while(getche()=='y'); } void main() { Int t[size]={0},wt[size]={0},min,p,sum=0,temp,i,j,k=0,l=0,m=0; clrscr(); get_mat(); t[1]=1; printf("\n\ntree includes following edges:"); for(p=1;p<=n-1;p++) { temp=1000; for(i=1;i<=n;i++) { if(t[i]==1) { min=1000; for(j=1;j<=n;j++) { if(cost[i][j]<min && t[j]==0) { min=cost[i][j];

k=j; } } if(min < temp) { temp=min; l=k; m=i; } } }wt[p]=cost[m][l]; sum=sum+wt[p]; printf("\nedge:%d%d wt:%d",m,l,cost[m][l]); t[l]=t[m]=1; } printf("\n\n weight of minimum spanning tree: %d",sum); getch(); } OUTPUT: Enter the no. of vertices:5 Enter the edge & their weight(v1 v2,wt):1 2 3 Continue:y Enter the edge & their weight(v1 v2,wt):1 4 3 Continue:y Enter the edge & their weight(v1 v2,wt):2 3 1 Continue:y Enter the edge & their weight(v1 v2,wt):3 4 2 Continue:y Enter the edge & their weight(v1 v2,wt):2 5 4 Continue:y

Enter the edge & their weight(v1 v2,wt):4 5 3 Continue:y Enter the edge & their weight(v1 v2,wt):3 5 1 Continue:n tree includes following edges: edge:12 wt:3 edge:23 wt:1 edge:35 wt:1 edge:34 wt:2 weight of minimum spanning tree: 7

RESULT:

Thus the Prim's algorithm using priority queues is implementedand MST of an undirected graph is found successfully.

You might also like