Minimum Spanning Tree (Prim’s Algorithm)

#include<stdio.h>

int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],visited[9];

void main()
{
    printf("Enter the no. of vertices ");
    scanf("%d",&n);
    printf("Enter the cost adjacency matrix\n");
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {
            scanf("%d",&cost[i][j]);
            if(cost[i][j]==0)
                cost[i][j]=999;
        }
    }
    printf("Enter starting vertex ");
    scanf("%d",&k);
    visited[k]=1;
    printf("\nThe edges of Minimum Cost Spanning Tree are\n");
    while(ne<n)
    {
        for(i=1,min=999;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                if(cost[i][j]<min && visited[i]!=0)
                {
                    min=cost[i][j];
                    a=u=i;
                    b=v=j;
                }
            }
        }
        if(visited[u]==0 || visited[v]==0)
        {
            printf("Edge %d to %d = %d\n",a,b,min);
            mincost=mincost+min;
            visited[b]=1;
            ne++;
        }
        cost[a][b]=cost[b][a]=999;
    }
    printf("\nMinimum cost = %d",mincost);
}

/*Output
Enter the no. of vertices 6
Enter the cost adjacency matrix
0 7 0 10 0 0
7 0 5 0 0 5
0 5 0 3 0 4
10 0 3 0 15 0
0 0 0 15 0 2
0 5 4 0 2 0
Enter starting vertex 1

The edges of Minimum Cost Spanning Tree are
Edge 1 to 2 = 7
Edge 2 to 3 = 5
Edge 3 to 4 = 3
Edge 3 to 6 = 4
Edge 6 to 5 = 2

Minimum cost = 21
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s