Prim's Algorithm: Theory
Prim's Algorithm: Theory
Theory:
Code:
#include<stdio.h>
#include <time.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
int main()
{
printf("\nEnter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the 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;
}
visited[1]=1;
printf("\n");
double starttime=clock();
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]< min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
double endtime=clock();
printf("\n Minimun cost=%d",mincost);
printf("\nThe time taken is %f\n",(endtime-starttime)/CLOCKS_PER_SEC);
return 0;
}
Output:
Krushkal’s Algorithm:
Theory:
Code:
#include<stdio.h>
#include<time.h>
struct edge
{
int u,v,cost;
};
typedef struct edge edge;
e[j].u=e[j+1].u;
e[j].v=e[j+1].v;
e[j].cost=e[j+1].cost;
e[j+1].u=temp.u;
e[j+1].v=temp.v;
e[j+1].cost=temp.cost;
}
}
}
for(i=0;i<n;i++)
parent[i]=i;
p=0;
while(count!=n-1)
{
u=e[p].u;
v=e[p].v;
i=find(u,parent);
j=find(v,parent);
if(i!=j)
{
t[k][0]=u;
t[k][1]=v;
k++;
count++;
sum+=e[p].cost;
union_ij(i,j,parent);
}
p++;
}
if(count==n-1)
{
printf("Spanning tree exists\n");
printf("The spanning tree is as follows:\n");
for(i=0;i<n-1;i++)
{
printf("%d-->%d\n",t[i][0],t[i][1]);
}
printf("\nThe cost of the spanning tree is %d\n",sum);
}
else
printf("\n spanning tree does not exist");
}
int main()
{
int n,m,a,b,i,cost;
edge e[20];
printf("Enter the number of vertices:");
scanf("%d",&n);
printf("Enter the number of edges:\n");
scanf("%d",&m);
printf("Enter the edge list( u v cost)\n");
for(i=0;i<m;i++)
{
scanf("%d%d%d",&a,&b,&cost);
e[i].u=a;
e[i].v=b;
e[i].cost=cost;
}
double starttime=clock();
kruskal(n,e,m);
double endtime=clock();
printf("The time taken is %f\n",(endtime-starttime)/CLOCKS_PER_SEC);
return 0;
}
Output:
p