Sie sind auf Seite 1von 41

DAA LAB

JAWAHARLAL NEHRU NATIONAL COLLEGE OF


ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL
ON
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY (10CSL47)

PREPARED BY:
NARENDRA KUMAR S

DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY


(Common to CSE & ISE)
Subject Code: 10CSL47
I.A. Marks: 25
Hours/Week: 03
Exam Hours: 03
Total Hours: 42
Exam Marks: 50

_______________________________________________________________________________
Dept.of CSE
-1NARENDRA KUMAR S

DAA LAB

Design, develop and implement the specified algorithms for the following problems
using C/C++ Language in LINUX / Windows environment.
1. Sort a given set of elements using the Quicksort method and determine the time required to sort the
elements. Repeat the experiment for different values of n, the number of elements in the list to be
sorted and plot a graph of the time taken versus n. The elements can be read from a file or can be
generated using the random number generator.
2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort a given set of elements and
determine the time required to sort the elements. Repeat the experiment for different values of n,
the number of elements in the list to be sorted and plot a graph of the time taken versus n. The
elements can be read from a file or can be generated using the random number generator.
3. a. Obtain the Topological ordering of vertices in a given digraph.
b. Compute the transitive closure of a given directed graph using Warshalls algorithm.
4. Implement 0/1 Knapsack problem using Dynamic Programming.
5. From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstras algorithm.
6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskals algorithm.
7. a. Print all the nodes reachable from a given starting node in a digraph using BFS method.
b. Check whether a given graph is connected or not using DFS method.
8. Find a subset of a given set S = {sl, s2,.....,sn} of n positive integers whose sum is equal to a given
positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions
{1,2,6}and{1,8}.A suitable message is to be displayed if the given problem instance doesnt have a
solution.
9. Implement any scheme to find the optimal solution for the Traveling Salesperson problem and then
solve the same problem instance using any approximation algorithm and determine the error in the
approximation.
10. Find Minimum Cost Spanning Tree of a given undirected graph using Prims algorithm.
11. Implement All-Pairs Shortest Paths Problem using Floyds algorithm. Parallelize this algorithm,
implement it using OpenMP and determine the speed-up achieved.
12. Implement N Queens problem using Back Tracking.
Note: In the examination each student picks one question from the lot of all12 questions.

/* ASSIGNMENT 1. Sort a given set of elements using the Quicksort method and determine
the time required to sort the elements. Repeat the experiment for different values of n, the
number of elements in the list to be sorted and plot a graph of the time taken versus n. The
elements can be read from a file or can be generated using the random number generator. */
ALGORITHM: partition(a[0.n-1],lower,upper)
_______________________________________________________________________________
Dept.of CSE
-2NARENDRA KUMAR S

DAA LAB

//partition the array into parts such that elements towards the left of the key element are
//less than key element and elements towards right of the key element are greater than key
element
//Input: An array a[0.n-1] is unsorted from index position low to high
//Output: A partition of a[0n-1] with split position returned as this functions value
keya[low]
ilow+1
jhigh
while(j>i)
while ( a[i] <=key&&i<upper)
i++ ;
end while
while ( a[j] > key )
j-- ;
end while
if j>i
swap a[i] and a[j]
end if
end while
swap a[lower] and a[j]
return j
ALGORITHM: quick_sort(a[0.n-1],low,high)
//Sorts the elements of the array between lower bound low and upper bound high
//Input: An array a[0.n-1] is unsorted from index position low to high
//Output: Array a[0.n-1] is sorted in nondecreasing order
if low<high
jpartition(a,low,high)
quick_sort(a,low,j-1)
quick_sort(a,j+1,high)
end if
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
int *a,n;
int partition(int lower,int upper)
{
int l, i, j, t ;
i = lower + 1 ;
j = upper ;
key = a[lower] ;
while ( j > i )
_______________________________________________________________________________
Dept.of CSE
-3NARENDRA KUMAR S

DAA LAB

{
while ( a[i] <=key&&i<upper)
i++ ;
while ( a[j] > key )
j-- ;
if ( j> i )
{
t = a[i] ;
a[i] = a[j] ;
a[j] = t ;
}
}
t = a[lower] ;
a[lower] = a[j] ;
a[j] = t ;
return j ;
}
void quick(int low,int high)
{
int j;
if(low<high)
{
j=partition(low,high);
quick(low,j-1);
quick(j+1,high);
}
}
void main()
{
int i;
clock_t s,e;
clrscr();
printf("enter the size of unsorted list\n");
scanf("%d",&n);
a=(int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
{
a[i]=rand();
}
printf("an usorted list is\n");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
s=clock();
for(i=0;i<10;i++)
quick(0,n-1);
e=clock();
_______________________________________________________________________________
Dept.of CSE
-4NARENDRA KUMAR S

DAA LAB

printf("a sorted list is:\n");


for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n total time taken=%f\n",(double)((e-s)/CLOCKS_PER_SEC/10));
getch();
}
==========Output=============

enter the size of unsorted list


10
an usorted list is
346 130 10982 1090 11656 7117 17595 6415 22948 31126
a sorted list is:
130 346 1090 6415 7117 10982 11656 17595 22948 31126
total time taken=0.000000
(NOTE: run this program for input size 500, 1000, 1500 etc and then plot graph I/P size
V/s time.)

/* ASSIGNMENT 2. Using OpenMP, implement a parallelized Merge Sort algorithm to sort


a given set of elements and determine the time required to sort the elements. Repeat the
experiment for different values of n, the number of elements in the list to be sorted and plot a
graph of the time taken versus n. The elements can be read from a file or can be generated
using the random number generator. */
_______________________________________________________________________________
Dept.of CSE
-5NARENDRA KUMAR S

DAA LAB

ALGORITHM : mergesort ( A [ 0..n -1 ],low,high )


// Sorts array A [ 0 .n -1] by recursive mergesort
//Input: An array A [ 0..n -1 ] of orderable elements
//Output: Array A [ 0.n -1 ] Sorted in nondecreasing order.

if(low<high) then
mid (low+high)/2;
mergesort(low,mid);
mergesort(mid+1,high);
merge(low,mid,high);
end if
merge ( low,mid,high )
//Merges two sorted arrays into one sorted array
//Input: index low, mid and high of sorted array
//Output: Sorted array A [0n -1] of the elements of the unsorted array

il; jm+1; kl;


while(i<=m && j<=h) do
if( a[i] <a[j]) then
{b[k] a[i]; i++; }
else
{ b[k] a[j]; j++; }
k++;
end if
end while
while ( i<=m) do
b[k] a[i]; k++; i++;
end while
while(j<=h) do
b[k] a[j]; k++; j++;
end while
for il to h do
a[i] b[i];
end for
PROGRAM:
# include <stdio.h>
# include <omp.h>
# include <time.h>
_______________________________________________________________________________
Dept.of CSE
-6NARENDRA KUMAR S

DAA LAB

#include <stdlib.h>
int a[10000],b[10000];
void merge(int l,int m,int h)
{
int i,j,k;
i=l; j=m+1; k=l;
while(i<=m && j<=h)
{
if( a[i] <a[j])
{ b[k]=a[i]; i++; }
else
{ b[k]=a[j]; j++; }
k++;
}
while ( i<=m)
{
b[k]=a[i]; k++; i++;
}
while(j<=h)
{
b[k]=a[j]; k++; j++;
}
for(i=l;i<=h;i++)
a[i]=b[i];
}
void mergesort(int l,int h)
{
if(l<h)
{
int m=(l+h)/2;
mergesort(l,m);
mergesort(m+1,h);
merge(l,m,h);
}
}
_______________________________________________________________________________
Dept.of CSE
-7NARENDRA KUMAR S

DAA LAB

void read_mat(int n)
{
int i;
for(i=1;i<=n;i++)
a[i]=(int) rand()%10000;
}
void print_mat(int lb,int n)
{
int i;
for(i=lb;i<=n;i++)
printf("\t%d",a[i]);
}

main()
{
int i,j,n,type,k;
struct timeval start,end;
long mtime,s,us;
printf("\n Enter number of elements \n");
scanf("%d",&n);
read_mat(n);
printf("\n UNSORTED ARRAY \n");
print_mat(1,n);
printf("\n\n");
k=n/2;
gettimeofday(&start,0);
#pragma omp sections
{
#pragma omp section
{
mergesort(1,k);
printf("\n\nstart first half\n");
print_mat(1,k);
printf("\n\nend first half");
}
#pragma omp section
_______________________________________________________________________________
Dept.of CSE
-8NARENDRA KUMAR S

DAA LAB

{
mergesort(k+1,n);
printf("\n\nstart second half\n");
print_mat(k+1,n);
printf("\n\nend second half\n");
}
}
merge(1,k,n);
gettimeofday(&end,0);
s=end.tv_sec-start.tv_sec;
us=end.tv_usec-start.tv_usec;
printf("\n AFTER SORTING \n");
print_mat(1,n);
printf("\n");
printf("usertime=%lf\n",1-(s-us)/1000000.0F);
}
==========Output=============
enter number of elements
10
UNSORTED ARRAY
340 130 25 700 90 30 400 800 300 60
start first half
25 90 130 340 700
end first half
start second half
30 60 300 400 800
end second half
AFTER SORTING
25 30 60 90 130 300 340 400 700 800
usertime= 0.08878

/* ASSIGNMENT 3 a. Obtain the Topological ordering of vertices in a given digraph. */


ALGORITHM: topological_sort(a[1n,1.n])
// To obtain the sequence of jobs to be executed resulting in topological order.
//Input: The adjacency matrix a [1.n,1.n] of a given graph with n vertices.
//Output: Array t [0n-1] indicates the jobs that are to be executed in the order.
top-1
k0
for j1 to n do
sum0
for i1 to n do
sumsum+a[i][j]
end for

_______________________________________________________________________________
Dept.of CSE
-9NARENDRA KUMAR S

DAA LAB

indegree[j] sum
end for
for j1 to n do
if indegree[i]=0 then
toptop+1
s[top] i
end if
end for
while top != -1
us[top]
toptop+1
t[k++]u
for v1 to n do
if a[u][v] = 1 then
indegree[v]= indegree[v]-1
if indegree[v] = 0 then
toptop+1
s[top] v
end if
end if
end for
end while
write Topological Sequence is
for i0 to k-1 do
write t[i]
end for
PROGRAM:
#include<stdio.h>
#include<conio.h>
int indegree[20],t[20],a[20][20],n;
void t_sort()
{
int top=-1,k=0,i,j,sum=0,s[20],u,v;
for(j=1;j<=n;j++)
{
sum=0;
for(i=1;i<=n;i++)
sum=sum+a[i][j];
indegree[j]=sum;
}
for(i=1;i<=n;i++)
{
if(indegree[i]==0)
{
top=top+1;
s[top]=i;
}
}
while(top!=-1)
{u=s[top];

_______________________________________________________________________________
Dept.of CSE
- 10 NARENDRA KUMAR S

DAA LAB

top=top-1;
t[k++]=u;
for(v=1;v<=n;v++)
{
if(a[u][v]==1)
{
indegree[v]--;
if(indegree[v]==0)
{
top=top+1;
s[top]=v;
}
}
}
}
printf("\n Topological sequence is: \n");
for(i=0;i<k;i++)
printf("%d\t",t[i]);
}
void main()
{
int i,j;
clrscr();
printf("enter the value of n\n");
scanf("%d",&n);
printf("enter the adjacency matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
}
t_sort();
getch();
}
==========Output=============
enter the value of n
5
enter the adjacency matrix
00100
00100
00011
00001
00000
Topological sequence is:
2
1
3
4
5

_______________________________________________________________________________
Dept.of CSE
- 11 NARENDRA KUMAR S

DAA LAB

/*ASSIGNMENT 3 b. Compute the transitive closure of a given directed graph using


Warshall's algorithm. */
ALGORITHM: warshalls(a[1n,1.n])
// Implements Warshalls algorithm for computing the transitive closure
//Input: The adjacency matrix a[1.n,1.n] of a digraph with n vertices
//Output: The transitive closure of the digraph
for k1 to n do
for i1 to n do
for j1 to n do
if a[i,j]!=1
if a[i,k]=1 and a[k,j]=1
a[i,j]1
end if
end if
end for
end for
end for

_______________________________________________________________________________
Dept.of CSE
- 12 NARENDRA KUMAR S

DAA LAB

write path matrix is


for i1 to n do
for j1 to n do
write a[i,j]
end for
end for
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[10][10],n;
void warshalls();
void main()
{
int i,j;
clrscr();
printf("\nenter the no. of vertices:\t");
scanf("%d",&n);
printf("\nenter the adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
warshalls();
getch();
}
void warshalls()
{
int i,j,k;
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(a[i][j]!=1)
{
if(a[i][k]==1&&a[k][j]==1)
{
a[i][j]=1;
}
}
}
}
}
printf("\npath matrix is:\n");
for(i=1;i<=n;i++)
{

_______________________________________________________________________________
Dept.of CSE
- 13 NARENDRA KUMAR S

DAA LAB

for(j=1;j<=n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n\n");
}
}
==========Output=============
Enter the no. of vertices: 4
Enter the adjacency matrix:
0 1 0 0
0 0 1 0
1 0 0 1
0 0 0 0
Path matrix is:
1 1 1 1
1 1 1 1
1 1 1 1
0 0 0 0

/* ASSIGNMENT 4.

Implement 0/1 Knapsack problem using Dynamic Programming. */

ALGORITHM : knapsack(w[1n],p[1n],n,m)
//To find the optimal solution for the Knapsack problem using dynamic programming
// Input: n-number of objects to be selected, m-maximum capacity of the Knapsack
//
An array w[1.n] contains weights of all objects
//
An array p[1.n] contains profits of all objects
// Output :A matrix v[0.n,0.m] contains the optimal solution for the number of objects
selected with specified remaining capacity
for i0 to n do
for j0 to m do
if i=0 or j=0
v[i,j]=0
else if j-w[i]<0
v[i,j]=v[i-1,j]
else
v[i,j]=max(v[i-1,j],v[i-1,j-w[i]+p[i])
end if
end for
end for
write the output is
for i0 to n do
for j0 to m do
write v[i,j]
end for

_______________________________________________________________________________
Dept.of CSE
- 14 NARENDRA KUMAR S

DAA LAB

end for
write the optimal solution is,v[n,m]
write solution vector is
for in downto 1 do
if v[i,m]!=v[i-1,m]
x[i]1
mm-w[i]
else
x[i]0
end if
end for
for i1 to n do
write x[i]
end for
return
PROGRAM:
#include<stdio.h>
#include<conio.h>
void knapsack();
int max(int,int);
int i,j,n,m,p[10],w[10],v[10][10];
void main()
{
clrscr();
printf("\nenter the no. of items:\t");
scanf("%d",&n);
printf("\nenter the weight of the each item:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&w[i]);
}
printf("\nenter the profit of each item:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&p[i]);
}
printf("\nenter the knapsack's capacity:\t");
scanf("%d",&m);
knapsack();
getch();
}
void knapsack()
{
int x[10];
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
if(i==0||j==0)

_______________________________________________________________________________
Dept.of CSE
- 15 NARENDRA KUMAR S

DAA LAB

{
v[i][j]=0;
}
else if(j-w[i]<0)
{
v[i][j]=v[i-1][j];
}
else
{
v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
}
}
}
printf("\nthe output is:\n");
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
printf("%d\t",v[i][j]);
}
printf("\n\n");
}
printf("\nthe optimal solution is %d",v[n][m]);
printf("\nthe solution vector is:\n");
for(i=n;i>=1;i--)
{
if(v[i][m]!=v[i-1][m])
{
x[i]=1;
m=m-w[i];
}
else
{
x[i]=0;
}
}
for(i=1;i<=n;i++)
{
printf("%d\t",x[i]);
}
}
int max(int x,int y)
{
if(x>y)
{
return x;
}
else
{
return y;
}
}
==========Output=============

_______________________________________________________________________________
Dept.of CSE
- 16 NARENDRA KUMAR S

DAA LAB

Enter the no. of items: 4


Enter the weight of each item:
2 1 3 2
Enter the profit of the each item:
12 10 20 15
Enter the Knapsacks capacity: 5
The output is:
0 0 0 0 0
0
0 0 12 12 12 12
0 10 12 22 22 22
0 10 12 22 30 32
0 10 15 25 30 37
The optimal solution is: 37
The solution vector is:
1 1 0 1

/* ASSIGNMENT 5. From a given vertex in a weighted connected graph, find shortest paths
to other vertices using Dijkstra's algorithm. */
ALGORITHM: dijkstras(c[1.n,1.n],src)
//To compute shortest distance from given source node to all nodes of a weighted
undirected graph
//Input: An nXn cost matrix c[1n,1.n] with source node src
//Output: The length dist[j] of a shortest path from src to j.
for j1 to n do
dist[j]c[src,[j]
end for
for j1 to n do
vis[j]0
end for
dist[src]0
vis[src]1
count1
while count!=n do
min9999
for j1 to n do
if dist[j]<min and vis[j]!=1
mindist[j]
uj
end if
end for
vis[u]1
countcount+1
for j1 to n do
if min+c[u,j]<dist[j] and vis[j]!=1
dist[j]min+c[u,j]
end if
end for

_______________________________________________________________________________
Dept.of CSE
- 17 NARENDRA KUMAR S

DAA LAB

end while
write shortest distance is
for j1 to n do
write src,j,dist[j]
end for
PROGRAM:
#include<stdio.h>
#include<conio.h>
void dijkstras();
int c[10][10],n,src;
void main()
{
int i,j;
clrscr();
printf("\nenter the no of vertices:\t");
scanf("%d",&n);
printf("\nenter the cost matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&c[i][j]);
}
}
printf("\nenter the source node:\t");
scanf("%d",&src);
dijkstras();
getch();
}
void dijkstras()
{
int vis[10],dist[10],u,j,count,min;
for(j=1;j<=n;j++)
{
dist[j]=c[src][j];
}
for(j=1;j<=n;j++)
{
vis[j]=0;
}
dist[src]=0;
vis[src]=1;
count=1;
while(count!=n)
{
min=9999;
for(j=1;j<=n;j++)
{
if(dist[j]<min&&vis[j]!=1)
{

_______________________________________________________________________________
Dept.of CSE
- 18 NARENDRA KUMAR S

DAA LAB

min=dist[j];
u=j;
}
}
vis[u]=1;
count++;
for(j=1;j<=n;j++)
{
if(min+c[u][j]<dist[j]&&vis[j]!=1)
{
dist[j]=min+c[u][j];
}
}
}
printf("\nthe shortest distance is:\n");
for(j=1;j<=n;j++)
{
printf("\n%d----->%d=%d",src,j,dist[j]);
}
}
==========Output=============
Enter the no. of vertices: 5
Enter the cost matrix:
9999
3 9999
7
3 9999
4
2
9999
4 9999
5
7
2
5 9999
9999 9999
6
4

9999
9999
6
4
9999

Enter the source node: 1


The shortest distance is:
1-----------> 1 = 0
1-----------> 2 = 3
1-----------> 3 = 7
1-----------> 4 = 5
1-----------> 5 = 9

_______________________________________________________________________________
Dept.of CSE
- 19 NARENDRA KUMAR S

DAA LAB

/* ASSIGNMENT 6. Find Minimum Cost Spanning Tree of a given undirected graph using
Kruskal's algorithm. */
ALGORITHM: kruskals(c[1n,1n])
//To compute the minimum spanning tree of a given weighted undirected graph using
Kruskals
// algorithm
//Input: An nXn cost matrix c[1n,1.n]
//Output: minimum cost of spanning tree of given undirected graph
ne0
mincost0
for i1 to n do
parent[i]0
end for
while ne!=n-1 do
min9999
for i1 to n do
for j1 to n do
if c[i,j]<min
minc[i,j]
ui
ai
vj
bj
end if
end for
end for
while parent[u]!=0 do
uparent[u]
end while
while parent[v]!=0 do
vparent[v]
end while
if u!= v
write a,b,min
parent[v]u
nene+1

_______________________________________________________________________________
Dept.of CSE
- 20 NARENDRA KUMAR S

DAA LAB

mincostmincost+min
end if
c[a,b]9999
c[b,a]9999
end while
write mincost
return
PROGRAM:
#include<stdio.h>
#include<conio.h>
void kruskals();
int c[10][10],n;
void main()
{
int i,j;
clrscr();
printf("\nenter the no. of vertices:\t");
scanf("%d",&n);
printf("\nenter the cost matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&c[i][j]);
}
}
kruskals();
getch();
}
void kruskals()
{
int i,j,u,v,a,b,min;
int ne=0,mincost=0;
int parent[10];
for(i=1;i<=n;i++)
{
parent[i]=0;
}
while(ne!=n-1)
{
min=9999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(c[i][j]<min)
{
min=c[i][j];
u=a=i;
v=b=j;

_______________________________________________________________________________
Dept.of CSE
- 21 NARENDRA KUMAR S

DAA LAB

}
}
}
while(parent[u]!=0)
{
u=parent[u];
}
while(parent[v]!=0)
{
v=parent[v];
}
if(u!=v)
{
printf("\n%d----->%d=%d\n",a,b,min);
parent[v]=u;
ne=ne+1;
mincost=mincost+min;
}
c[a][b]=c[b][a]=9999;
}
printf("\nmincost=%d",mincost);
}
==========Output=============
Enter the no. of vertices: 6
Enter the cost matrix:
9999
3 9999 9999
3 9999
1 9999
9999
1 9999
6
9999
6
6 9999
6 9999 9999
8
5
4
4
5

6
9999
9999
8
9999
2

5
4
4
5
2
9999

2-----------> 3 = 1
5-----------> 6 = 2
1-----------> 2 = 3
2-----------> 6 = 4
4-----------> 6 = 5
Mincost = 15

_______________________________________________________________________________
Dept.of CSE
- 22 NARENDRA KUMAR S

DAA LAB

/* ASSIGNMENT 7 a. Print all the nodes reachable from a given starting node in a digraph
using BFS method. */
ALGORITHM : bfs(a[1.n,1.n],src)
// Implements a breadth-first traversal of a given digraph
//Input: An adjacency matrix a[1.n,1.n] of given digraph ,src-from where the traversal is
initiated
//Output: The digraph with its vertices marked with consecutive integers in the order they
have been //visited by the BFS traversal mark each vertex in vis[1.n] with 0 as mark of
being node is not //reachable
for j1 to n do
vis[j]0
end for
f0
r-1
vis[src]1
rr+1
while f<=r do
iq[f]
ff+1
for j1 to n do
if a[i,j]=1 and vis[j]!=1
vis[j]1
rr+1
q[r]j
end if
end for
end while
for j1 to n do
if vis[j]!=1
write node is not reachable
else
write node is reachable
end if
end for
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[10][10],n;
void bfs(int);

_______________________________________________________________________________
Dept.of CSE
- 23 NARENDRA KUMAR S

DAA LAB

void main()
{
int i,j,src;
clrscr();
printf("\nenter the no of nodes:\t");
scanf("%d",&n);
printf("\nenter the adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nenter the source node:\t");
scanf("%d",&src);
bfs(src);
getch();
}
void bfs(int src)
{
int q[10],f=0,r=-1,vis[10],i,j;
for(j=1;j<=n;j++)
{
vis[j]=0;
}
vis[src]=1;
r=r+1;
q[r]=src;
while(f<=r)
{
i=q[f];
f=f+1;
for(j=1;j<=n;j++)
{
if(a[i][j]==1&&vis[j]!=1)
{
vis[j]=1;
r=r+1;
q[r]=j;
}
}
}
for(j=1;j<=n;j++)
{
if(vis[j]!=1)
{
printf("\nnode %d is not reachable\n",j);
}
else
{
printf("\nnode %d is reachable\n",j);
}
}

_______________________________________________________________________________
Dept.of CSE
- 24 NARENDRA KUMAR S

DAA LAB

==========Output=============
Enter the no. of nodes: 6
Enter the adjacency matrix:
0 1 1 1 0 0
0 0 0 0 1 0
0 0 0 0 1 1
0 0 0 0 0 1
0 0 0 0 0 0
0 0 0 0 1 0
Enter the source node: 1
Node 1 is reachable
Node 2 is reachable
Node 3 is reachable
Node 4 is reachable
Node 5 is reachable
Node 6 is reachable

_______________________________________________________________________________
Dept.of CSE
- 25 NARENDRA KUMAR S

DAA LAB

/* ASSIGNMENT 7 b. Check whether a given graph is connected or not using DFS method.
*/
ALGORITHM : dfs(a[1.n,1.n],src)
// Implements a depth-first traversal of a given digraph
//Input: An adjacency matrix a[1.n,1.n] of given digraph, src-from where the traversal is
initiated
//Output: returns 0 if graph is not connected otherwise 1 is returned
vis[src]1
for j1 to n do
if a[src,j]=1 and vis[j]!=1
dfs(j)
end if
end for
for j1 to n do
if vis[j]!=1
write graph is not connected
end if
end for
write graph is connected
return
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[10][10],n,vis[10];
int dfs(int);
void main()
{
int i,j,src,ans;
clrscr();
for(j=1;j<=n;j++)
{
vis[j]=0;
}
printf("\nenter the no of nodes:\t");
scanf("%d",&n);
printf("\nenter the adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nenter the source node:\t");
scanf("%d",&src);
ans=dfs(src);
if(ans==1)

_______________________________________________________________________________
Dept.of CSE
- 26 NARENDRA KUMAR S

DAA LAB

{
printf("\ngraph is connected\n");
}
else
{
printf("\ngragh is not connected\n");
}
getch();
}
int dfs(int src)
{
int j;
vis[src]=1;
for(j=1;j<=n;j++)
{
if(a[src][j]==1&&vis[j]!=1)
{
dfs(j);
}
}
for(j=1;j<=n;j++)
{
if(vis[j]!=1)
{
return 0;
}
}
return 1;
}
==========Output=============
Enter the no. of nodes: 4
Enter the adjacency matrix:
0 1 1 0
0 0 0 0
0 0 0 1
0 1 0 0
Enter the source node: 1
Graph is connected
Enter the no. of nodes: 4
Enter the adjacency matrix:
0 1 1 0
0 0 0 0
0 1 0 0
0 0 0 0
Enter the source node: 1
Graph is not connected

/* ASSIGNMENT 8. Find a subset of a given set S = {sl, s2,.....,sn} of n positive integers


whose sum is equal to a given positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9
there are two solutions {1,2,6}and{1,8}.A suitable message is to be displayed if the given
problem instance doesn't have a solution. */
_______________________________________________________________________________
Dept.of CSE
- 27 NARENDRA KUMAR S

DAA LAB

ALGORITHM: subset(s[1.n],d)
// To find subsets of a given set of n positive integers whose sum is equal to a given
positive integer d
//Input: An array s[1.n] of sorted elements, d-required sum
//Output: subsets of given set s[1.n] whose elements sum is equal to d.
x[k]1
if m+s[k]=d
write subset solution is, countcount+1
for i0 to k do
if x[i]=1
write s[i]
end if
end for
else if m+s[k]+s[k+1]<=d
subset(m+s[k],k+1,sum-s[k])
end if
if m+sum-s[k]>=d and m+s[k+1]<=d
x[k]0
subset(m,k+1,sum-s[k])
end if
PROGRAM:
#include<stdio.h>
#include<conio.h>
void subset(int,int,int);
int count=0,d,s[10],x[10];
void main()
{
int sum=0, i,n;
clrscr();
printf("\nenter no. of elements:\t");
scanf("%d",&n);
printf("\nenter the elements in ascending order:\n");
for(i=0;i<=n-1;i++)
{
scanf("%d",&s[i]);
}
printf("\nenter the required sum:\t");
scanf("%d",&d);
for(i=0;i<=n-1;i++)
{
sum=sum+s[i];
}
if(sum<d||s[0]>d)
{
printf("no solution exists\n");
}
else
{
subset(0,0,sum);

_______________________________________________________________________________
Dept.of CSE
- 28 NARENDRA KUMAR S

DAA LAB

}
getch();
}
void subset(int m,int k,int sum)
{
int i;
x[k]=1;
if(m+s[k]==d)
{
printf("\nsubset solution %d is\n",++count);
for(i=0;i<=k;i++)
{
if(x[i]==1)
{
printf("%d\t",s[i]);
}
}
}
else if(m+s[k]+s[k+1]<=d)
{
subset(m+s[k],k+1,sum-s[k]);
}
if((m+sum-s[k]>=d)&&(m+s[k+1]<=d))
{
x[k]=0;
subset(m,k+1,sum-s[k]);
}
}
==========Output=============
Enter the no. of elements: 5
Enter the elements in ascending order:
1 2 5 6 8
Enter the required sum: 9
Subset solution 1 is
1 2 6
Subset solution 2 is
1 8

/* ASSIGNMENT 9. Implement any scheme to find the optimal solution for the Traveling
Salesperson problem and then solve the same problem instance using any approximation
algorithm and determine the error in the approximation. */
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=(t))

_______________________________________________________________________________
Dept.of CSE
- 29 NARENDRA KUMAR S

DAA LAB

int v[100],vis[100],pres[100],c[100][100], n,src;


float sum,min=999,min1=999;
void perm(int i)
{
int j,temp;
if(i==n && v[1]==src)
{
sum=0;
for(j=1;j<=n;j++)
{
printf("%d\t",v[j]);
if(j<n)
sum=sum+c[v[j]][v[j+1]];
}
sum=sum+c[v[j-1]][v[1]];
printf("%d = %f\n",v[1],sum);
if(sum<min)
{
min=sum;
for(j=1;j<=n;j++)
pres[j]=v[j];
}
}
else
{
for(j=i;j<=n;j++)
{
SWAP(v[i],v[j],temp);
perm(i+1);
SWAP(v[i],v[j],temp);
}
}
}
void es()
{
int i;
printf("\nfeasible solutions are\n");
perm(1);
printf("\noptimal solution with exhaustive search method is\n\n");
for(i=1;i<=n;i++)
printf("%d\t",pres[i]);
printf("%d = %f\n",pres[1],min);
}
void nn()
{
int p,i,j,from;
vis[src]=1;
from=src;
sum=0;
printf("\n solution with nearest neighbour method is \n");
printf("%d\t",src);
for(j=1;j<n;j++)

_______________________________________________________________________________
Dept.of CSE
- 30 NARENDRA KUMAR S

DAA LAB

{
min1=999;
for(i=1;i<=n;i++)
{
if(vis[i]!=1 && c[from][i]<min1 && c[from][i]!=0)
{
min1=c[from][i];
p=i;
}
}
vis[p]=1;
from=p;
sum=sum+min1;
printf("%d\t",p);
}
sum=sum+c[from][src];
printf("%d ",src);
printf(" = %f\n",sum);
}
void main()
{
int i,j;
float re;
clrscr();
printf("\n enter no. of vertices\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
v[i]=i;
vis[i]=0;
}
printf("enter the cost matrix of the graph\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
printf("enter the source vertex\n");
scanf("%d",&src);
es();
nn();
re=((sum/min)-1)*100;
printf("\n the relative error percentage is = %f",re);
getch();
}
==========Output=============
enter no. of vertices
4
enter the cost matrix of the graph
0136
1023
3201
6310
enter the source vertex
1

_______________________________________________________________________________
Dept.of CSE
- 31 NARENDRA KUMAR S

DAA LAB

feasible solutions are


1
2
3
4
1 = 10.000000
1
2
4
3
1 = 8.000000
1
3
2
4
1 = 14.000000
1
3
4
2
1 = 8.000000
1
4
3
2
1 = 10.000000
1
4
2
3
1 = 14.000000
optimal solution with exhaustive search method is
1
2
4
3
1 = 8.000000
solution with nearest neighbour method is
1
2
3
4
1 = 10.000000
the relative error percentage is = 25.000000

/* ASSIGNMENT 10. Find Minimum Cost Spanning Tree of a given undirected graph using
Prims algorithm. */
ALGORITHM: prims(c[1n,1n])
//To compute the minimum spanning tree of a given weighted undirected graph using
Prims
// algorithm
//Input: An nXn cost matrix c[1n,1.n]
//Output: minimum cost of spanning tree of given undirected graph
ne0
mincost0
for i1 to n do
elec[i]1
end for
elec[1]1
while ne!=n-1 do
min9999
for i1 to n do

_______________________________________________________________________________
Dept.of CSE
- 32 NARENDRA KUMAR S

DAA LAB

for j1 to n do
if elec[i]=1
if c[i,j]<min
minc[i,j]
ui
vj
end if
end if
end for
end for
if elec[v]!=1
write u,v,min
elec[v]1
nene+1
mincostmincost+min
end if
c[u,v]9999
c[v,u]9999
end while
write mincost
return
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<process.h>
void prims();
int c[10][10],n;
void main()
{
int i,j;
clrscr();
printf("\nenter the no. of vertices:\t");
scanf("%d",&n);
printf("\nenter the cost matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&c[i][j]);
}
}
prims();
getch();
}
void prims()
{
int i,j,u,v,min;
int ne=0,mincost=0;
int elec[10];

_______________________________________________________________________________
Dept.of CSE
- 33 NARENDRA KUMAR S

DAA LAB

for(i=1;i<=n;i++)
{
elec[i]=0;
}
elec[1]=1;
while(ne!=n-1)
{
min=9999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(elec[i]==1)
{
if(c[i][j]<min)
{
min=c[i][j];
u=i;
v=j;
}
}
}
}
if(elec[v]!=1)
{
printf("\n%d----->%d=%d\n",u,v,min);
elec[v]=1;
ne=ne+1;
mincost=mincost+min;
}
c[u][v]=c[v][u]=9999;
}
printf("\nmincost=%d",mincost);
}
==========Output=============
Enter the no. of vertices: 6
Enter the cost matrix:
9999
3 9999 9999
3 9999
1 9999
9999
1 9999
6
9999
6
6 9999
6 9999 9999
8
5
4
4
5

6
9999
9999
8
9999
2

5
4
4
5
2
9999

2-----------> 3 = 1
5-----------> 6 = 2
1-----------> 2 = 3
2-----------> 6 = 4
4-----------> 6 = 5
Mincost = 15

_______________________________________________________________________________
Dept.of CSE
- 34 NARENDRA KUMAR S

DAA LAB

/* ASSIGNMENT 11. Implement All-Pairs Shortest Paths Problem using Floyd's algorithm.
Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved.
*/
ALGORITHM: floyds(a[1.n,1.n])
//Implements Floyds algorithm for all-pairs shortest path problem
//Input: cost matrix a[1.n,1.n] of size nXn
//Output: Shortest distance matrix a[1.n,1.n] of size nXn
for k1 to n do
for i1 to n do
for j1 to n do
a[i,j]min(a[i,j],a[i,k]+a[k,j])
end for
end for
end for
write all pair shortest path matrix is
for i1 to n do
for j1 to n do
write a[i,j]
end for
end for
PROGRAM:

_______________________________________________________________________________
Dept.of CSE
- 35 NARENDRA KUMAR S

DAA LAB

#include<stdio.h>
#include<sys/time.h>
#include<stdlib.h>
#include<unistd.h>
#include<omp.h>
int n,c[10][10],d[10][10];
int min(int,int);
void read_data();
void write_data();
void floyds();
void write_data()
{
int i,j;
printf("the least distance matrix is\n ");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",d[i][j]);
}
printf("\n");
}
}
void floyds()
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
d[i][j]=c[i][j];
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
}
void floydsp()
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
d[i][j]=c[i][j];
#pragma omp sections
{
#pragma omp section

_______________________________________________________________________________
Dept.of CSE
- 36 NARENDRA KUMAR S

DAA LAB

for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
}
}
}
}
}
int min(int a,int b)
{
if(a<b)
return a;
return b;
}
void read_data()
{
int i,j;
printf("enter the number of vertices\n");
scanf("%d",&n);
printf("enter the cost matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&c[i][j]);
}
}
}
int main()
{
struct timeval start,end;
long s,us;
read_data();
gettimeofday(&start,0);
floyds();
gettimeofday(&end,0);
s=end.tv_sec-start.tv_sec;
us=end.tv_usec-start.tv_usec;
printf("\n usertime by serial=%lf\n",1+(s-us)/1000000.0F);
gettimeofday(&start,0);
floydsp();
gettimeofday(&end,0);
s=end.tv_sec-start.tv_sec;
us=end.tv_usec-start.tv_usec;
printf("\n usertime by parallel=%lf\n",1+(s-us)/1000000.0F);
printf("\n complete\n");
write_data();
}
==========Output=============

_______________________________________________________________________________
Dept.of CSE
- 37 NARENDRA KUMAR S

DAA LAB

Enter the no. of vertices: 4


Enter the cost matrix:
9999 9999
3 9999
2 9999 9999 9999
9999
7 9999
1
6 9999 9999 9999
usertime by serial=0.99999
usertime by parallel=0.99876
the least distance matrix is
10 10
3
4
2 12
5
6
7
7 10
1
6 16
9 10

/* ASSIGNMENT 12. Implement N Queen's problem using Back Tracking. */


ALGORITHM: nqueens(n)
//places n queens on a nXn matrix such that no two queens are placed along same row or
same column
//or same diagonal using backtracking method.
//Input: n-number of queens.
//Output: k-the queen k, x[k]-the position of queen k.
k1
x[k]0
while k!=0 do
x[k]x[k]+1
while place(x,k)!=1 and x[k]<=n do
x[k]x[k]+1
end while
if x[k]<=n
if k=n
for k1 to n do
write k,x[k]
printf(k,x);
end for
else
kk+1
x[k]0
end if
else
kk-1
end if
end while
ALGORITHM: place(x[k],k)

_______________________________________________________________________________
Dept.of CSE
- 38 NARENDRA KUMAR S

DAA LAB

//places n queens on a nXn matrix such that no two queens are placed along same row or
same column
//or same diagonal using backtracking method.
//Input: k-the queen k, x[k]- position of queen k.
//Output: returns 0 if any two queens are placed along same diagonal or same column
otherwise 1 is returned.
for i1 to k-1 do
if i-x[i]=k-x[k] or i+x[i]=k+x[k] or x[i]=x[k]
return 0
end if
end for
return 1
PROGRAM:
#include<stdio.h>
#include<conio.h>
void nqueens(int);
int place(int[],int);
void prin(int n,int x[])
{
char c[10][10];
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
c[i][j]='X';
}
}
for(i=1;i<=n;i++)
{
c[i][x[i]]='Q';
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%c",c[i][j]);
}
printf("\n");
}
}
void main()
{
int n;
clrscr();
printf("\nenter the no of queens:\t");
scanf("%d",&n);
if(n==2 || n==3)
printf("no solution for %d queens\n",n);

_______________________________________________________________________________
Dept.of CSE
- 39 NARENDRA KUMAR S

DAA LAB

else
nqueens(n);
getch();
}
void nqueens(int n)
{
int k,x[10],count=0;
k=1;
x[k]=0;
while(k!=0)
{
x[k]++;
while(place(x,k)==1&&x[k]<=n)
{
x[k]++;
}
if(x[k]<=n)
{
if(k==n)
{
printf("\nsolution %d is\n",++count);
for(k=1;k<=n;k++)
printf("%d----->%d\n",k,x[k]);
printf("\n solution in the form of chess board\n");
prin(n,x);
}
else
{
k++;
x[k]=0;
}
}
else
{
k--;
}
}
}
int place(int x[],int k)
{
int i;
for(i=1;i<=k-1;i++)
{
if(i-x[i]==k-x[k]||i+x[i]==k+x[k]||x[i]==x[k])
{
return 1;
}
}
return 0;
}
==========Output=============

_______________________________________________________________________________
Dept.of CSE
- 40 NARENDRA KUMAR S

DAA LAB

enter the no of queens: 4


solution 1 is
1----->2
2----->4
3----->1
4----->3
solution in the form of chess board
XQXX
XXXQ
QXXX
XXQX
solution 2 is
1----->3
2----->1
3----->4
4----->2
solution in the form of chess board
XXQX
QXXX
XXXQ
XQXX

_______________________________________________________________________________
Dept.of CSE
- 41 NARENDRA KUMAR S

Das könnte Ihnen auch gefallen