Lab Programs On Design and Analysis of Algorithms
Lab Programs On Design and Analysis of Algorithms
Program 10:Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm.
/*Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.*/
#include
#include
#include
min=9999;
source=0;
for(i=0;i{
for(j=0;j{
if(cost[i][j] !=0 && cost[i][j]<=min)
{
min=cost[i][j];
source=i;
}
}
}
for(i=0;i{
d[i]=cost[source][i];
s[i]=0;
p[i]=source;
}
s[source]=1;
sum=0;
k=0;
for(i=1;i{
min=9999;
u=-1;
for(j=0;j{
if(s[j]==0)
{
if(d[j]<=min)
{
min=d[j];
u=j;
}
}
}
t[k][0]=u;
t[k][1]=p[u];
k++;
sum+=cost[u][p[u]];
s[u]=1;
for(v=0;v{
if(s[v]==0 && cost[u][v]{
d[v]=cost[u][v];
p[v]=u;
}
}
}
if(sum>=9999)
printf("Spanning tree does not exist\n");
else
{
printf("Spanning tree exists and minimum spanning tree is \n");
for(i=0;i{
printf("%d %d \n",t[i][0],t[i][1]);
}
printf("\n The cost of the spanning tree = %d",sum);
}
}
clrscr();
prims(n,cost);
getch();
}
/*--------------------------OUTPUT:Sample-------------------------
Enter the number of nodes
4
Enter the cost adjacency matrix
0 20 10 9999
20 0 9999 30
10 9999 0 40
9999 30 40 0
Spanning tree exists and minimum spanning tree is
02
10
31
Program 11: Implement All-Pairs Shortest Paths Problem using Floyd's algorithm.
for(i=0;i{
for(j=0;j{
d[i][j]=cost[i][j];
}
}
for(k=0;k{
for(i=0;i{
for(j=0;j{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
}
for(i=0;i{
for(j=0;jscanf("%d",&a[i][j]);
}
}
for(i=0;i{
for(j=0;j{
printf("%5d",a[i][j]);
}
printf("\n");
}
}
void main()
{
int n, cost[10][10],d[10][10];
clrscr();
floyd(n,cost,d);
printf("Solution to all-pairs shortest-paths problem is\n");
write_matrix(n,d);
getch();
}
/*------------------OUTPUT:Sample--------------------------------------
Enter the number of nodes:4
#define TRUE 1
#define FALSE 0
void nqueens(int n)
{
int x[10];
int count=0;/*Number of solutions*/
int k=1;/*Select the first queen*/
void main()
{
int n;
clrscr();
if(n==1||n==2||n==3)
{
printf("\nNo solution exists");
}
else
nqueens(n);
getch();
}
/*------------------OUTPUT:Sample-------------------------
Enter the number of queens:4
Solution 1 is
*Q**
***Q
Q***
**Q*
Solution 2 is
**Q*
Q***
***Q
*Q**
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n;/* Number of cities. */
int i,j,c[max][max];/* Loop counters. */
int tour[max];/* Cost matrix. */
cost;/* Least cost. */
clrscr();
for(i=0;i<n;i++)
tour[i]=i;
cost=tspdp(c,tour,0,n);
printf("\nTour:\n");
for(i=0;i<n;i++)
printf("%d - ",tour[i]+1);
printf("1\n");
getch();
/* Adjust positions. */
temp[start+1]=tour[i];
temp[i]=tour[start+1];