The BOTTOM LINE Quote Of The Day

The BOTTOM LINE Quote Of The Day

Don't Ever Tell GOD How BIG Your Problems are.
Just Tell Your Problems How BIG your GOD is ;)

Thursday, May 3, 2012

Kruskal's Algorithm 2


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define INFNITY 999

int a[10][10],n,p[10];
voidprintArray(){
inti,j;
for(i=0;i<n;i++)
    {
for(j=0;j<n;j++)
        {
printf("%d\t",a[i][j]);
        }
printf("\n");
    }
}
voiduAdjacencyMatrix(){
inti,j,c=1,w;
for(i = 0;i < n; i++)
    {
for(j = 0;j < i; j++)
        {
a[i][j] = INFNITY;
a[j][i] = INFNITY;

        }
a[i][i] = INFNITY;

    }

while(c!=-1)
    {
printf ("\ni , j , w :");           
scanf("%d%d%d",&i,&j,&w);
a[i][j]=a[j][i]=w;
     //printf ("c? :");
scanf("%d",&c);
    }
printArray();
getch();
}


intfindParent(int a)
{
while(a!=p[a])
     a=p[a];
return a;
}


void unite(inta,int b)
{
inti,j;
     i=findParent(a);
     j=findParent(b);
if(i<j)
p[j]=i;
else
p[i]=j;

}
voidsetParent()
{
int i;
for (i=0;i<n;i++)
p[i]=i;
}

inttotalEdges()
{
inti,j,count=0;
for (i=0;i<n;i++)
      {
for(j=0;j<i;j++)
       {
if(a[i][j]!=INFNITY)
count++;
       }   
      }
      //printf("Count : %d",count);
return count;
}

voidminEdge(int *aa,int *bb)
{
inti,j,w=INFNITY;

for (i=0;i<n;i++)
      {
for(j=0;j<i;j++)
       {
if(a[i][j]<w)
          {
          w=a[i][j];
          *aa=i;
          *bb=j;
          }          
       }   
      }

}
int main()
{

printf("enter the number of vertices : ");
scanf("%d",&n);
uAdjacencyMatrix();
setParent();
intcount,u=0,v=0,w=0;
count=totalEdges();
while(count>0)
    {
minEdge(&u,&v);          
if(findParent(u) != findParent(v))
       {
if(u<v)
printf("\n%d --> %d",u,v);
else
printf("\n%d --> %d",v,u);
w+=a[u][v];
unite(u,v);                
       }


a[u][v]=a[v][u]=INFNITY;
count--;
    }

printf("\nWeight : %d",w);

getch();
return(0);

}

No comments:

Post a Comment