DAA Lab Manual VTU
Post on 21-Oct-2015
1249 Views
Preview:
DESCRIPTION
Transcript
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
_______________________________________________________________________________Dept.of CSE - 1 - NARENDRA KUMAR S
DAA LAB
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
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 Warshall’s 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 Dijkstra’s algorithm.
6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s 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 doesn’t 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 Prim’s algorithm.
11. Implement All-Pairs Shortest Paths Problem using Floyd’s algorithm. Parallelize this algorithm, implement it using OpenMP and determine the speed-up achieved.
12. Implement N Queen’s problem using Back Tracking.
Note: In the examination each student picks one question from the lot of all12 questions.
_______________________________________________________________________________Dept.of CSE - 2 - NARENDRA KUMAR S
DAA LAB
/* 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)//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[0…n-1] with split position returned as this function’s value
keya[low]ilow+1jhighwhile(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 ifend 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){_______________________________________________________________________________Dept.of CSE - 3 - NARENDRA KUMAR S
DAA LAB
int l, i, j, t ;i = lower + 1 ;j = upper ;key = a[lower] ;while ( j > i ){
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]); }_______________________________________________________________________________Dept.of CSE - 4 - NARENDRA KUMAR S
DAA LAB
printf("\n"); s=clock(); for(i=0;i<10;i++) quick(0,n-1); e=clock(); 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 list10an usorted list is346 130 10982 1090 11656 7117 17595 6415 22948 31126a 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.)
_______________________________________________________________________________Dept.of CSE - 5 - NARENDRA KUMAR S
DAA LAB
/* 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. */
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 [0…n -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 ifend while
while ( i<=m) dob[k] a[i]; k++; i++;
end while
while(j<=h) dob[k] a[j]; k++; j++; end while
for il to h doa[i] b[i];
end for
_______________________________________________________________________________Dept.of CSE - 6 - NARENDRA KUMAR S
DAA LAB
PROGRAM:
# include <stdio.h># include <omp.h># include <time.h>#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){
_______________________________________________________________________________Dept.of CSE - 7 - NARENDRA KUMAR S
DAA LAB
if(l<h) {
int m=(l+h)/2;mergesort(l,m);mergesort(m+1,h);merge(l,m,h);
}}
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
_______________________________________________________________________________Dept.of CSE - 8 - NARENDRA KUMAR S
DAA LAB
{#pragma omp section{
mergesort(1,k);printf("\n\nstart first half\n");print_mat(1,k);printf("\n\nend first half");
}
#pragma omp section{
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 elements10UNSORTED ARRAY340 130 25 700 90 30 400 800 300 60start first half 25 90 130 340 700end first halfstart second half 30 60 300 400 800end second halfAFTER SORTING 25 30 60 90 130 300 340 400 700 800usertime= 0.08878
_______________________________________________________________________________Dept.of CSE - 9 - NARENDRA KUMAR S
DAA LAB
/* ASSIGNMENT 3 a. Obtain the Topological ordering of vertices in a given digraph. */
ALGORITHM: topological_sort(a[1…n,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 [0…n-1] indicates the jobs that are to be executed in the order.
top-1k0for j1 to n do
sum0 for i1 to n do
sumsum+a[i][j]end forindegree[j] sum
end forfor j1 to n do if indegree[i]=0 then
toptop+1s[top] i
end ifend forwhile top != -1
us[top]toptop+1
t[k++]ufor v1 to n do
if a[u][v] = 1 thenindegree[v]= indegree[v]-1if indegree[v] = 0 then
toptop+1s[top] v
end ifend if
end forend whilewrite ‘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;
_______________________________________________________________________________Dept.of CSE - 10 - NARENDRA KUMAR S
DAA LAB
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]; 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();}
_______________________________________________________________________________Dept.of CSE - 11 - NARENDRA KUMAR S
DAA LAB
==========Output=============
enter the value of n5enter the adjacency matrix0 0 1 0 00 0 1 0 00 0 0 1 10 0 0 0 10 0 0 0 0 Topological sequence is:2 1 3 4 5
_______________________________________________________________________________Dept.of CSE - 12 - NARENDRA KUMAR S
DAA LAB
/*ASSIGNMENT 3 b. Compute the transitive closure of a given directed graph using Warshall's algorithm. */
ALGORITHM: warshalls(a[1…n,1….n])// Implements Warshall’s 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 forend forwrite ‘ path matrix is’for i1 to n do for j1 to n do write a[i,j] end forend 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();}
_______________________________________________________________________________Dept.of CSE - 13 - NARENDRA KUMAR S
DAA LAB
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++) { for(j=1;j<=n;j++) { printf("%d\t",a[i][j]); } printf("\n\n"); }}
==========Output=============
Enter the no. of vertices: 4Enter the adjacency matrix:0 1 0 00 0 1 01 0 0 10 0 0 0Path matrix is:1 1 1 11 1 1 11 1 1 10 0 0 0
_______________________________________________________________________________Dept.of CSE - 14 - NARENDRA KUMAR S
DAA LAB
/* ASSIGNMENT 4. Implement 0/1 Knapsack problem using Dynamic Programming. */
ALGORITHM : knapsack(w[1…n],p[1…n],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 forend forwrite ‘the output is’for i0 to n do for j0 to m do write v[i,j] end forend forwrite ‘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 ifend forfor i1 to n do write x[i]end forreturn 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];
_______________________________________________________________________________Dept.of CSE - 15 - NARENDRA KUMAR S
DAA LAB
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) { 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]);
_______________________________________________________________________________Dept.of CSE - 16 - NARENDRA KUMAR S
DAA LAB
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=============
Enter the no. of items: 4Enter the weight of each item:2 1 3 2Enter the profit of the each item:12 10 20 15Enter the Knapsack’s capacity: 5The output is:0 0 0 0 0 0 0 0 12 12 12 120 10 12 22 22 220 10 12 22 30 320 10 15 25 30 37The optimal solution is: 37The solution vector is:1 1 0 1
_______________________________________________________________________________Dept.of CSE - 17 - NARENDRA KUMAR S
DAA LAB
/* 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[1…n,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 forfor j1 to n do vis[j]0end fordist[src]0vis[src]1count1while 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 forend whilewrite ‘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);
_______________________________________________________________________________Dept.of CSE - 18 - NARENDRA KUMAR S
DAA LAB
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) { 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++) {
_______________________________________________________________________________Dept.of CSE - 19 - NARENDRA KUMAR S
DAA LAB
printf("\n%d----->%d=%d",src,j,dist[j]); }}
==========Output=============
Enter the no. of vertices: 5
Enter the cost matrix:9999 3 9999 7 9999 3 9999 4 2 99999999 4 9999 5 6 7 2 5 9999 49999 9999 6 4 9999
Enter the source node: 1
The shortest distance is:1-----------> 1 = 01-----------> 2 = 31-----------> 3 = 71-----------> 4 = 51-----------> 5 = 9
_______________________________________________________________________________Dept.of CSE - 20 - NARENDRA KUMAR S
DAA LAB
/* ASSIGNMENT 6. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm. */
ALGORITHM: kruskals(c[1…n,1…n])//To compute the minimum spanning tree of a given weighted undirected graph using Kruskal’s// algorithm//Input: An nXn cost matrix c[1…n,1….n]//Output: minimum cost of spanning tree of given undirected graph
ne0mincost0for i1 to n do parent[i]0end forwhile 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 mincostmincost+min end if c[a,b]9999 c[b,a]9999end whilewrite mincostreturn
PROGRAM:
#include<stdio.h>#include<conio.h>
void kruskals();int c[10][10],n;
_______________________________________________________________________________Dept.of CSE - 21 - NARENDRA KUMAR S
DAA LAB
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; } } } while(parent[u]!=0) { u=parent[u]; } while(parent[v]!=0) { v=parent[v]; } if(u!=v)
_______________________________________________________________________________Dept.of CSE - 22 - NARENDRA KUMAR S
DAA LAB
{ 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 6 5 3 9999 1 9999 9999 49999 1 9999 6 9999 49999 6 6 9999 8 5 6 9999 9999 8 9999 2 5 4 4 5 2 9999
2-----------> 3 = 15-----------> 6 = 21-----------> 2 = 32-----------> 6 = 44-----------> 6 = 5
Mincost = 15
_______________________________________________________________________________Dept.of CSE - 23 - 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]0end forf0r-1vis[src]1rr+1while 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 forend whilefor j1 to n do if vis[j]!=1 write ‘node is not reachable’ else write ‘node is reachable’ end ifend for
PROGRAM:
#include<stdio.h>#include<conio.h>
int a[10][10],n;void bfs(int);
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++)
_______________________________________________________________________________Dept.of CSE - 24 - NARENDRA KUMAR S
DAA LAB
{ 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 - 25 - NARENDRA KUMAR S
DAA LAB
==========Output=============
Enter the no. of nodes: 6Enter the adjacency matrix:0 1 1 1 0 00 0 0 0 1 00 0 0 0 1 10 0 0 0 0 10 0 0 0 0 00 0 0 0 1 0Enter the source node: 1Node 1 is reachableNode 2 is reachableNode 3 is reachableNode 4 is reachableNode 5 is reachableNode 6 is reachable
_______________________________________________________________________________Dept.of CSE - 26 - 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]1for j1 to n do if a[src,j]=1 and vis[j]!=1 dfs(j) end ifend forfor j1 to n do if vis[j]!=1 write ‘graph is not connected’ end ifend forwrite ‘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 - 27 - 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: 4Enter the adjacency matrix:0 1 1 00 0 0 00 0 0 10 1 0 0Enter the source node: 1Graph is connected
Enter the no. of nodes: 4Enter the adjacency matrix:0 1 1 00 0 0 00 1 0 00 0 0 0Enter the source node: 1Graph is not connected
_______________________________________________________________________________Dept.of CSE - 28 - NARENDRA KUMAR S
DAA LAB
/* 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. */
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]1if 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 forelse if m+s[k]+s[k+1]<=d subset(m+s[k],k+1,sum-s[k])end ifif 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)
_______________________________________________________________________________Dept.of CSE - 29 - NARENDRA KUMAR S
DAA LAB
{ printf("no solution exists\n"); } else { subset(0,0,sum); } 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: 5Enter the elements in ascending order:1 2 5 6 8
Enter the required sum: 9Subset solution 1 is1 2 6Subset solution 2 is1 8
_______________________________________________________________________________Dept.of CSE - 30 - NARENDRA KUMAR S
DAA LAB
/* 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))
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++)
_______________________________________________________________________________Dept.of CSE - 31 - NARENDRA KUMAR S
DAA LAB
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++) {
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();
_______________________________________________________________________________Dept.of CSE - 32 - NARENDRA KUMAR S
DAA LAB
nn();re=((sum/min)-1)*100;printf("\n the relative error percentage is = %f",re);getch();
}==========Output=============
enter no. of vertices4enter the cost matrix of the graph0 1 3 61 0 2 33 2 0 16 3 1 0enter the source vertex1feasible solutions are1 2 3 4 1 = 10.0000001 2 4 3 1 = 8.0000001 3 2 4 1 = 14.0000001 3 4 2 1 = 8.0000001 4 3 2 1 = 10.0000001 4 2 3 1 = 14.000000optimal solution with exhaustive search method is1 2 4 3 1 = 8.000000 solution with nearest neighbour method is1 2 3 4 1 = 10.000000 the relative error percentage is = 25.000000
_______________________________________________________________________________Dept.of CSE - 33 - NARENDRA KUMAR S
DAA LAB
/* ASSIGNMENT 10. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm. */
ALGORITHM: prims(c[1…n,1…n])//To compute the minimum spanning tree of a given weighted undirected graph using Prim’s// algorithm//Input: An nXn cost matrix c[1…n,1….n]//Output: minimum cost of spanning tree of given undirected graph
ne0mincost0for i1 to n do elec[i]1end forelec[1]1while ne!=n-1 do min9999 for i1 to n do 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]9999end whilewrite mincostreturn
PROGRAM:
#include<stdio.h>#include<conio.h>#include<process.h>
void prims();int c[10][10],n;
void main(){ int i,j;
_______________________________________________________________________________Dept.of CSE - 34 - NARENDRA KUMAR S
DAA LAB
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]; 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; }
_______________________________________________________________________________Dept.of CSE - 35 - NARENDRA KUMAR S
DAA LAB
printf("\nmincost=%d",mincost);}
==========Output=============
Enter the no. of vertices: 6
Enter the cost matrix:9999 3 9999 9999 6 5 3 9999 1 9999 9999 49999 1 9999 6 9999 49999 6 6 9999 8 5 6 9999 9999 8 9999 2 5 4 4 5 2 9999
2-----------> 3 = 15-----------> 6 = 21-----------> 2 = 32-----------> 6 = 44-----------> 6 = 5
Mincost = 15
_______________________________________________________________________________Dept.of CSE - 36 - 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 Floyd’s 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 forend forwrite ‘all pair shortest path matrix is’for i1 to n do for j1 to n do write a[i,j] end forend for
PROGRAM:
#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");}
}
_______________________________________________________________________________Dept.of CSE - 37 - NARENDRA KUMAR S
DAA LAB
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 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);
_______________________________________________________________________________Dept.of CSE - 38 - NARENDRA KUMAR S
DAA LAB
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=============
Enter the no. of vertices: 4
Enter the cost matrix:9999 9999 3 99992 9999 9999 99999999 7 9999 1 6 9999 9999 9999usertime by serial=0.99999usertime by parallel=0.99876the least distance matrix is 10 10 3 4 2 12 5 6 7 7 10 1 6 16 9 10
_______________________________________________________________________________Dept.of CSE - 39 - NARENDRA KUMAR S
DAA LAB
/* 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.
k1x[k]0while 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 ifend while
ALGORITHM: place(x[k],k)//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 ifend forreturn 1
PROGRAM:
#include<stdio.h>#include<conio.h>
void nqueens(int);int place(int[],int);
_______________________________________________________________________________Dept.of CSE - 40 - NARENDRA KUMAR S
DAA LAB
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); 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) {
_______________________________________________________________________________Dept.of CSE - 41 - NARENDRA KUMAR S
DAA LAB
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=============
enter the no of queens: 4solution 1 is1----->22----->43----->14----->3
solution in the form of chess boardXQXXXXXQQXXXXXQX
solution 2 is1----->32----->1
_______________________________________________________________________________Dept.of CSE - 42 - NARENDRA KUMAR S
DAA LAB
3----->44----->2
solution in the form of chess boardXXQXQXXXXXXQXQXX
_______________________________________________________________________________Dept.of CSE - 43 - NARENDRA KUMAR S
top related