Minimum Spanning Tree (Kruskal Algorithm)

#include<stdio.h>

int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);

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("\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)
                {
                    min=cost[i][j];
                    a=u=i;
                    b=v=j;
                }
            }
        }
        u=find(u);
        v=find(v);
        if(uni(u,v))
        {
            printf("Edge %d to %d = %d\n",a,b,min);
            ne++;
            mincost += min;
        }
        cost[a][b]=cost[b][a]=999;
    }
    printf("\nMinimum cost = %d",mincost);
}

int find(int i)
{
    while(parent[i])
        i=parent[i];
    return i;
}

int uni(int i,int j)
{
    if(i!=j)
    {
        parent[j]=i;
        return 1;
    }
    return 0;
}

/*Output:
Enter the no. of vertices 4
Enter the cost adjacency matrix
0 1 0 4
1 0 2 0
0 2 0 3
4 0 3 0

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

Minimum cost = 6
*/

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