Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Minimal Spanning Tree~Prims Alogorithm

Saturday, July 20, 2013

Minimal Spanning Tree~Prims Alogorithm

Minimal Spanning Tree by Prims Alogorithm


#include<stdio.h>
int main()
{
float graph[11][11],lcost[11],sum=0.0,min;
int close[11],i,j,k,n;
printf("\n Enter the number of vertices:\n");
do
   {
   scanf("%d",&n);
   if(n<=10)
       break;
   printf("\n Number of vertices cannot exceed 10:");
    }while(n>10);
for(i=1;i<=n;i++)
    graph[i][i]=0.0;
printf("\n Enter 999 if there is no edge between selected vertices:\n");
printf("\n Enter the weighted matrix:\n");
for(i=1;i<n;i++)
    for(j=i+1;j<=n;j++)
        {
        printf("\n Enter the cost of edge %d<--->%d : ",i,j);
        scanf("%f",&graph[i][j]);
        graph[j][i]=graph[i][j];
        }
printf("\nThe weighted matrix is:\n");
for(i=1;i<=n;i++)
    {
    for(j=1;j<=n;j++)
        {
        printf("%f\t  ",graph[i][j]);
        }
    printf("\n");
    }
for(i=2;i<=n;i++)
    {
    lcost[i]=graph[1][i];
    close[i]=1;
    }
printf("\n Minimum cost spanning tree by Prim's Algorithm are:\n");
    for(i=2;i<=n;i++)
    {
    min=lcost[2];
    k=2;
    for(j=3;j<=n;j++)
        if(lcost[j]<min)
        {
            min=lcost[j];
            k=j;
        }
    printf("Min=%f\n",min);
    sum +=min;
    printf(" %d<--->%d\n",k,close[k]);
    lcost[k]=1000.0;
    for(j=2;j<=n;j++)
        if((graph[k][j]<lcost[j]) && (lcost[j]<1000.0))
            {
            lcost[j]=graph[k][j];
            close[j]=k;
            }
    }
printf("\n Minimum cost is: %f\n",sum);
return 0;
}
   



No comments:

Post a Comment