#include<stdio.h>
#include<conio.h>
#include<string.h>
#define max 9
struct edge
{
char u;
char v;
int wuv;
int ind;
int tind;
}ed[max*max],tmp;
int ind[max];
int size;
void inp_dat()
{
int cho;
size = 0;
do
{
printf("\n Enter the vertices of edge and its weight : ");
scanf(" %c %c %d",&ed[size].u,&ed[size].v,&ed[size].wuv);
ed[size].ind = 0;
ed[size].tind = 0;
ind[ed[size].u-97] = 0;
ind[ed[size].v-97] = 0;
++size;
printf("\n\n Enter '0' to continue : ");
scanf("%d",&cho);
}while(cho == 0);
}
void sort_dat()
{
for(int i=0;i<size;i++)
{
for(int j=0;j<size-i-1;j++)
{
if(ed[j].wuv > ed[j+1].wuv)
{
tmp = ed[j];
ed[j] = ed[j+1];
ed[j+1] = tmp;
}
}
}
}
void disp_dat()
{
for(int i=0;i<size;i++)
printf("\n Edge '%c%c' weight : %d ",ed[i].u,ed[i].v,ed[i].wuv);
}
void kruskal()
{
char stack[max];
int ss;
int ret;
char tmp;
char dest;
for(int i=0;i<size;i++)
{
stack[0] = ed[i].u; dest = ed[i].v;
ss = 1; ret = 0;
for(int k=0;k<size;k++)
ed[k].tind = 0;
do
{
--ss; tmp = stack[ss];
for(int j=0;j<size;j++)
{
if(j != i)
{
if(ed[j].ind == 1 && ed[j].tind == 0)
{
if(tmp == ed[j].u)
{
if(dest == ed[j].v)
{
ret = 1; break;
}
else
{
stack[ss] = ed[j].v; ++ss;
ed[j].tind = 1;
}
}
if(tmp == ed[j].v)
{
if(dest == ed[j].u)
{
ret = 1; break;
}
else
{
stack[ss] = ed[j].u; ++ss;
ed[j].tind = 1;
}
}
}
}
if(ret == 1)
break;
}
}while(ss !=0 && ret == 0);
if(ret == 0)
{
ed[i].ind = 1;
ed[i].tind = 1;
}
}
printf("\n\n The Minimum Spanning Tree \n\n");
for(int k=0;k<size;k++)
{
if(ed[k].ind == 1)
printf("\n Edge '%c%c' weight : %d ",ed[k].u,ed[k].v,ed[k].wuv);
}
getch();
}
int main()
{
inp_dat();
printf("\n.. Before Sorting ..\n");
disp_dat();
sort_dat();
printf("\n.. After Sorting ..\n");
disp_dat();
printf("\n.. After Kruskal ..\n");
kruskal();
getch();
return 0;
}
No comments:
Post a Comment