Upload
-
View
215
Download
0
Embed Size (px)
Citation preview
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 1/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
ALGORITHMS LABORATORY SYLLABUS
Subject Code : 07MCA48 I.A. Marks : 25
Hours/Week : 03 Exam Hours : 03
Total Hours : 42 Exam Marks : 50
Implement the following using C/C++
1. Implement Recursive Binary Search and Linear Search and determine the timerequired to search an element. Repeat the experiment for different values of n, the
number of elements in the list to be searched and plot a graph of the time taken
versus n.
2. Sort a given set of elements using the Heapsort 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.
3. Sort a given set of elements using Merge sort method and determine the time
required to sort the elements. Repeat the experiment for different values of n, thenumber of elements in the list to be sorted and plot a graph of the time taken
versus n.
4. Sort a given set of elements using Selection sort and determine the time requiredto sort 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.
5. a. Obtain the Topological ordering of vertices in a given digraph.
b. Implement All Pair Shortest paths problem using Floyd’s algorithm.
6. Implement 0/1 Knapsack problem using dynamic programming.
7. From a given vertex in a weighted connected graph, find the shortest paths toother vertices using Dijkstra’s algorithm.
8. Sort a given set of elements using Quick sort method and determine the time
required to sort the elements. Repeat the experiment for different values of n, thenumber of elements in the list to be sorted and plot a graph of the time taken
versus n.
9. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’s
algorithm.
10. 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.
Gogte Institute of Technology Department of MCA 1
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 2/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
11. Find a subset of a given set S= {s1, 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 thegiven problem instance doesn’t have a solution.
12. a. Implement Horspool algorithm for String Matching.b. Find the Binomial Co-efficient using Dynamic Programming.
13. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’salgorithm.
14. a. Implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problem.
b.Compute the transitive closure of a given directed graph using Warshall’salgorithm.
15. Implement N Queen’s problem using Back Tracking.
Note: In the examination questions must be given based on lots.
Gogte Institute of Technology Department of MCA 2
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 3/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
SOLUTIONS FOR THE LAB ASSIGNMENTS
1. Implement Recursive Binary Search and Linear Search and determine the timerequired to search an element. Repeat the experiment for different values of n, the
number of elements in the list to be searched and plot a graph of the time taken versus
n.
#include<stdio.h>
#include<conio.h>#include<time.h>
#define MAX 1000
#define u 1000
#define v 10000
int binsearch(int,int,int);
int linsearch(int,int,int);
int a[MAX];void main()
{int pos,key,i,n; /*Declaration of variables*/
int x,y;
clock_t start,end;
clrscr(); printf("Enter the array size:\n");
scanf("%d",&n);
printf("Enter the elements:\n");for(i=0;i<n;i++)
{
a[i]=i+1; /*Read the elements*/ printf("%d\t",a[i]); /*Print the read elements*/
}
printf("\nEnter key element:\n");scanf("%d",&key);
start=clock(); /*Computing Binary Search Start time*/
for(x=0;x<u;x++)
for(y=0;y<v;y++)pos=binsearch(0,n-1,key);
end=clock();
if(pos<0)printf("Key not found:\n");
else
printf("Key found:\n");printf("Time for Binary Search: %.2f secs\n",(end-start)/CLK_TCK);
//getch();
start=clock(); /*Computing Linear Search start time*/
for(x=0;x<u;x++)
Gogte Institute of Technology Department of MCA 3
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 4/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
for(y=0;y<v;y++)
pos=linsearch(0,n-1,key);
end=clock();if(pos<0)
printf("Key not found:\n");
elseprintf("Key found:\n");
printf("Time for Linear Search: %.2f secs\n",(end-start)/CLK_TCK);
getch();}
int binsearch(int low, int high, int key)
{int mid;
if(low<=high)
{
mid=(low+high)/2; /*Computing middle term*/if(key==a[mid])
return mid;else if(key<a[mid]) /*Compare with key element*/
binsearch(low,mid-1,key);
else
binsearch(mid+1,high,key);}
else
{return -1;
}
}
int linsearch(int low, int high, int key)
{if(low<=high)
{
if(a[high]==key) /*Compare highest element with key element*/
{return high;
}
else{
linsearch(low,high-1,key);
}}
else
{
return -1;
Gogte Institute of Technology Department of MCA 4
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 5/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
}
}
Output
Enter the array size:25
Enter the elements:
1 2 3 4 5 6 7 8 9 1011 12 13 14 15 16 17 18 19 20
21 22 23 24 25
Enter key element:
18Key found:
Time for Binary Search: 1.37 secs
Key found:
Time for Linear Search: 1.21 secs
Enter the array size:50
Enter the elements:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 2021 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
Enter key element:
34Key found:
Time for Binary Search: 1.15 secs
Key found:Time for Linear Search: 2.97 secs
Enter the array size:
50Enter the elements:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 2021 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
Enter key element:
90
Key not found:
Gogte Institute of Technology Department of MCA 5
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 6/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Time for Binary Search: 1.81 secs
Key not found:
Time for Linear Search: 8.57 secs
Enter the array size:
100Enter the elements:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 2021 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 6061 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
Enter key element:99
Key found:
Time for Binary Search: 1.70 secs
Key found:Time for Linear Search: 0.27 secs
GraphsBinary Search
n time
10 1.15
25 1.43
40 1.7
75 1.98
Gogte Institute of Technology Department of MCA 6
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 7/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Graph of Binary Search
0
0.5
1
1.5
2
2.5
0 20 40 60 80
n
t i m e
time
Linear Searchn time
10 0.55
20 2.58
35 3.63
50 4.78
100 12.75
Graph of Linear Search
0
2
4
6
8
10
12
14
0 20 40 60 80 100 120
n
t i m e
time
2. Sort a given set of elements using the Heapsort 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.
Gogte Institute of Technology Department of MCA 7
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 8/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
/*Heap sort*/
#include<stdio.h>#include<conio.h>
#define MTIMES 100
#define NTIMES 10000#include<time.h>
#define MAX 100
void heapify(int a[],int n){
int i,j,v,heap,k;
for(i=n/2;i>0;i--)/*loop to work backward from an intermediate node at n/2 upto
the root node*/{
k=i;
v=a[i];/*remember the value at root node of the subtree*/
heap=0;while(!heap&&(2*k)<=n)/*check if we are well within array limits*/
{ j=2*k;/*Point to the children of i*/
if(j<n)/*If i has two children if yes compare the two child nodes*/
{
if(a[j]<a[j+1]){
j=j+1;/*point to the right child node if it is bigger*/
}}
if(v>=a[j]) /*Root node is bigger then child node check if ur done
with heapfing the subtree*/heap=1;
else
{a[k]=a[j]; /*Exchange with root*/
k=j;
}
}a[k]=v;/*finally copy the root node to the correct position so as to
maintain the heap property*/
}}
void heapsort(int a[],int n){
int temp,i,j;
heapify(a,n);
for(i=1;i<=n;i++)
Gogte Institute of Technology Department of MCA 8
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 9/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
{
for(j=i+1;j<=n;j++)
{if(a[i]>a[j])
{
temp=a[i];a[i]=a[j];
a[j]=temp;
}}
}
}
void main(){
int i,n,a[MAX+1],j;
clock_t start, end;
clrscr(); printf("Enter the value of n:");
scanf("%d",&n); printf("Enter the array element:");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
start=clock();for(i=0;i<MTIMES;i++)
for(j=0;j<NTIMES;j++)
heapsort(a,n);end=clock();
printf("The sorted elements are:");
for(i=1;i<=n;i++) printf("%d\t",a[i]);
printf("\nTime: %fsecs",(end-start)/CLK_TCK);
getch();
}
Output
Enter the value of n:5
Enter the array element:4 3 2 1 5The sorted elements are:1 2 3 4 5
Time: 0.274725secs
Enter the value of n:10
Enter the array element:45 22 11 55 67 43 12 34 54 10
The sorted elements are:10 11 12 22 34 43 45
54 55 67
Gogte Institute of Technology Department of MCA 9
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 10/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Time: 1.043956secs
Enter the value of n:20Enter the array element:20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
The sorted elements are:1 2 3 4 5 6 7
8 9 10 11 12 13 14 15 16 1718 19 20
Time: 3.791209secs
Graph
Heap Sort
n time
5 0.27
10 1.043
20 3.79
Graph of Heap Sort
0
0.5
1
1.5
2
2.5
3
3.5
4
0 10 20 30
n
t i m e
time
3. Sort a given set of elements using Merge sort method and determine the time requiredto 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.
/*To implete merge sort*/
#include<stdio.h>
#include<conio.h>#include<time.h>
#define M_TIMES 1000
#define N_TIMES 10000void main()
{
Gogte Institute of Technology Department of MCA 10
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 11/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
int a[100],i,n,j;
clock_t start,end;
clrscr();
printf("\nEnter the size of first array:");
scanf("%d",&n); printf("\nEnter the array element:");
for(i=0;i<n;i++)
{scanf("%d",&a[i]);
}
start=clock();
for(i=0;i<N_TIMES;i++)for(j=0;j<M_TIMES;j++)
mergesort(a,0,n-1);
end=clock(); printf("The sorted array is:");
for(i=0;i<n;i++) printf("%d\t",a[i]);
printf("\n The time required for sorting is:%.2f secs",(end-start)/(CLK_TCK));
getch();
}
mergesort(int a[],int low,int high)
{
int mid;
if(low<high){
mid=(low+high)/2; /*divide left and right sublists until they become
small*/mergesort(a,low,mid);
mergesort(a,mid+1,high);
simplemerge(a,low,mid,high); /*merge two sublists*/
}}
simplemerge(int a[],int low,int mid,int high)
{int i,j,k,c[100];
i=low;
j=mid+1;k=low;
while(i<=mid && j<=high)
{
if(a[i]<a[j])
Gogte Institute of Technology Department of MCA 11
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 12/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
{
c[k]=a[i]; /*Copy elements from left sublist*/
i=i+1;k=k+1;
}
else{
c[k]=a[j]; /*Copy elements from right sublist*/
j=j+1;k=k+1;
}
}
while(i<=mid){
c[k]=a[i]; /*Store remaining elements in temporary array*/
i=i+1;
k=k+1;}
while(j<=high){
c[k]=a[j]; /*Store remaining elements in temporary array*/
j++;
k++;}
for(i=low;i<=high;i++)
{a[i]=c[i];
}
}
Output
Enter the size of first array:3
Enter the array element:3 4 1
The sorted array is:1 3 4The time required for sorting is:1.98 secs
Enter the size of first array:5
Enter the array element:1 5 6 8 9
The sorted array is:1 5 6 8 9The time required for sorting is:4.23 secs
Enter the size of first array:10
Gogte Institute of Technology Department of MCA 12
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 13/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Enter the array element:10 9 8 7 6 5 4 3 2 1
The sorted array is:1 2 3 4 5 6 7 8
9 10The time required for sorting is:10.66 secs
Enter the size of first array:15
Enter the array element:2 4 3 1 6 5 8 7 9 10 13 12 11 14 15The sorted array is:1 2 3 4 5 6 7 8
9 10 11 12 13 14 15
The time required for sorting is:18.74 secs
Enter the size of first array:20
Enter the array element:20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1The sorted array is:1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17 1819 20
The time required for sorting is:25.99 secs
Graph
Merge Sort
n time
3 1.98
5 4.23
10 10.66
15 18.74
20 25.99
Gogte Institute of Technology Department of MCA 13
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 14/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Graph of Merge Sort
0
5
10
15
20
25
30
0 10 20 30
n
t i m e
time
4. Sort a given set of elements using Selection sort and determine the time required to
sort 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.
#include<stdio.h>
#include<conio.h>#include<time.h>
#define l 1000
#define m 10000
#define max 100
int a[max];
void sel_sort(int n);
main()
{int i,n,c,d;
clock_t start,end;
clrscr();
printf("\nA Program To Demonstrate Selection Sort ");
printf("\nEnter the array size:");scanf("%d",&n);
for(i=n;i>0;i--)
a[i] = i;
printf("\nUnsorted Array :\n ");
for(i=n;i>0;i--)
Gogte Institute of Technology Department of MCA 14
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 15/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
printf("%5d",a[i]);
start = clock();for(c=0;c<l;c++)
for(d=0;d<m;d++)
sel_sort(n-1);
end = clock();
printf("\nSorted Array is :\n");
for(i=1;i<=n;i++)
printf("%5d",a[i]);
printf("\nTime : %.2f",(end-start)/CLK_TCK);
getch();}
void sel_sort(int n)
{
int i,j,min,temp;
for(i=0;i<n-1;i++){
min = i;
for(j=j+1;j<n;j++){
if(a[j]<a[min])
min=j;}
temp = a[i];
a[i] = a[min];a[min] = temp;
}
}
Output
A Program To Demonstrate Selection SortEnter the array size:5
Unsorted Array :5 4 3 2 1
Sorted Array is :
1 2 3 4 5
Time : 0.27
Gogte Institute of Technology Department of MCA 15
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 16/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
A Program To Demonstrate Selection SortEnter the array size:10
Unsorted Array :10 9 8 7 6 5 4 3 2 1
Sorted Array is :
1 2 3 4 5 6 7 8 9 10Time : 0.77
A Program To Demonstrate Selection SortEnter the array size:15
Unsorted Array :
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1Sorted Array is :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15Time : 1.10
A Program To Demonstrate Selection SortEnter the array size:20
Unsorted Array :20 19 18 17 16 15 14 13 12 11 10 9 8 7 6
5 4 3 2 1
Sorted Array is :1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20
Time : 1.43
Graph
Selection Sort
n time
5 0.27
10 0.77
15 1.1
20 1.43
30 2.14
50 3.52
100 7.09
Gogte Institute of Technology Department of MCA 16
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 17/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Graph of Selection Sort
0
1
2
3
4
5
6
7
8
0 20 40 60 80 100 120
n
t i m e
time
5. a. Obtain the Topological ordering of vertices in a given digraph.
b. Implement All Pair Shortest paths problem using Floyd’s algorithm.
#include<stdio.h>
#define infinity 999
#include<conio.h>#define min(x,y)((x<y)?x:y);
void initgraph(int g[20][20],int n)
{
int i,j;
for(i=1;i<=n;i++)for(j=1;j<=n;j++)
g[i][j]=infinity;}
void readgraph(int g[20][20])
{int i,j,wt;
char ch;
do{
printf("\nInput directed edge<v1,v2,wt>:");
scanf("%d%d%d",&i,&j,&wt);g[i][j]=g[j][i]=wt;printf("One more edge?(y/n)");
ch=getche();
}while(ch=='y');
}
void printgraph(int a[20][20],int n)
Gogte Institute of Technology Department of MCA 17
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 18/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
{
int i,j;
for(i=1;i<=n;i++){
for(j=1;j<=n;j++)
printf("%5d",a[i][j]);printf("\n\n");
}
}void allpairs(int g[20][20],int n,int p[20][20])
{
int i,j,k;
for(i=1;i<=n;i++)for(j=1;j<=n;j++)
if(i==j)
p[i][j]=0;
elsep[i][j]=g[i][j];
for(k=1;k<=n;k++)for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
p[i][j]=min(p[i][j],p[i][k]+p[k][j]);/*Take minimun of two.
One from source to destination, sourceto intermediate k then k to destination*/
}
void main(){
int n,g[20][20],p[20][20];
clrscr(); printf("\nEnter how many nodes:");
scanf("%d",&n);
initgraph(g,n);readgraph(g);
allpairs(g,n,p);
printf("\n\nShortest path matrix:\n\n");
printgraph(p,n);getch();
}
Output
Enter how many nodes:5
Input directed edge<v1,v2,wt>:1 2 2
One more edge?(y/n)y
Input directed edge<v1,v2,wt>:1 3 5
Gogte Institute of Technology Department of MCA 18
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 19/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
One more edge?(y/n)y
Input directed edge<v1,v2,wt>:3 4 8
One more edge?(y/n)yInput directed edge<v1,v2,wt>:4 2 3
One more edge?(y/n)y
Input directed edge<v1,v2,wt>:3 5 2One more edge?(y/n)y
Input directed edge<v1,v2,wt>:5 4 9
One more edge?(y/n)n
Shortest path matrix:
0 2 5 5 72 0 7 3 9
5 7 0 8 2
5 3 8 0 9
7 9 2 9 0
6. Implement 0/1 Knapsack problem using dynamic programming.
#include<stdio.h>
#include<conio.h>
int max(int a, int b){
return a>b?a:b;
}void knapsack(int n, int w[],int m, int v[][10],int p[])
{
int i,j;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])v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);}
}
}void print_optimalsolution(int n, int m, int w[], int v[10][10])
{
int i,j,x[10];
printf("The optimal solution is %d\n",v[n][m]);
Gogte Institute of Technology Department of MCA 19
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 20/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
/*Initially no object has been selected*/
for(i=0;i<n;i++)
x[i]=0;i=n; /*number of objects*/
j=m; /*capacity of the knapsac*/
while(i!=0 && j!=0){
if(v[i][j]!=v[i-1][j])
{x[i]=1;/*ith object has been selected*/
j=j-w[i];/*obtain the remaining capacity of the knopsack*/
}
i=i-1;/*Select object among i-1 objects*/}
/*Output the objects selected*/
for(i=0;i<=n;i++)
{ printf("X[%d] ",i);
} printf("=");
for(i=1;i<=n;i++)
{
printf("%d ",x[i]);}
}
void main(){
int i,j,n,m,p[10],v[10][10],w[10];
clrscr(); printf("Enter the number of objects\n");
scanf("%d",&n);
printf("Enter the weights of n objects\n");for(i=1;i<=n;i++)
scanf("%d",&w[i]);
printf("Enter the profits of n objects\n");
for(i=1;i<=n;i++)scanf("%d",&p[i]);
printf("Enter the capacity of knapsack\n");
scanf("%d",&m);knapsack(n,w,m,v,p);
printf("The output is\n");
for(i=0;i<=n;i++){
for(j=0;j<=m;j++)
{
printf("%d\t",v[i][j]);
Gogte Institute of Technology Department of MCA 20
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 21/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
}
printf("\n");
} print_optimalsolution(n,m,w,v);
getch();
}
Output
Enter the number of objects
4
Enter the weights of n objects
21
3
2
Enter the profits of n objects12
1020
15
Enter the capacity of knapsack
5The output is
0 0 0 0 0 0
0 0 12 12 12 120 10 12 22 22 22
0 10 12 22 30 32
0 10 15 25 30 37The optimal solution is 37
X[0] X[1] X[2] X[3] X[4] =1 1 0 1
7. From a given vertex in a weighted connected graph, find the shortest paths to other
vertices using Dijkstra’s algorithm.
#include<stdio.h>#include<conio.h>
#define infinity 999
#define true 1#define false 0
void initgraph(int g[20][20],int n){
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
Gogte Institute of Technology Department of MCA 21
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 22/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
g[i][j]=infinity;/*initializing to infinity*/
}
void readgraph(int g[20][20]){
int i,j,wt;
char ch;do
{
printf("\nInput directed edge<v1,v2,wt>:");scanf("%d%d%d",&i,&j,&wt);
g[i][j]=wt;
printf("One more edge?(y/n):");
ch=getche();}
while(ch=='y');
}
void printgraph(int a[20][20],int n){
int i,j;for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{printf("%8d",a[i][j]);
}
printf("\n");}
}
int min(int a, int b){
return(a<b)?a:b; /*returns minimum value*/
}int minnode(int dist[],int n, int selected[])
{
int k, min=infinity,index=0;
for(k=1;k<=n;k++)if(dist[k]<min && selected[k]==false)
{
min=dist[k];index=k;
}
return index;}
void svspaths(int g[20][20], int n, int sv, int dist[])
{
int selected[20],k,u,w;
Gogte Institute of Technology Department of MCA 22
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 23/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
for(k=1;k<=n;k++)
{
selected[k]=false;/*Initially assume false*/dist[k]=g[sv][k];
}
selected[sv]=true;dist[sv]=0;
for(k=1;k<=n;k++)
{u=minnode(dist,n,selected);
selected[u]=true;
for(w=1;w<=n;w++)
if(selected[w]==false)dist[w]=min(dist[w],dist[u]+g[u][w]);/*take minimum of two*/
}
}
void main()
{int n, g[20][20], sv, dist[20];
int k;
clrscr();
printf("Enter how many node: ");scanf("%d",&n);
initgraph(g,n);
readgraph(g); printf("\nEnter the starting vertex:");
scanf("%d",&sv);
svspaths(g,n,sv,dist); printf("The given graph in matrix format:\n");
printgraph(g,n);
printf("\nSingle vertex shortest paths:\n");for(k=1;k<=n;k++)
printf("\nfrom node %d to node %d: %d",sv,k,dist[k]);
getch();
}
Output
Enter how many node: 4
Input directed edge<v1,v2,wt>:1 2 3One more edge?(y/n):y
Input directed edge<v1,v2,wt>:2 3 5
One more edge?(y/n):y
Input directed edge<v1,v2,wt>:3 4 6
Gogte Institute of Technology Department of MCA 23
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 24/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
One more edge?(y/n):y
Input directed edge<v1,v2,wt>:2 4 1
One more edge?(y/n):yInput directed edge<v1,v2,wt>:1 3 4
One more edge?(y/n):n
Enter the starting vertex:1The given graph in matrix format:
999 3 4 999
999 999 5 1999 999 999 6
999 999 999 999
Single vertex shortest paths:
from node 1 to node 1: 0
from node 1 to node 2: 3
from node 1 to node 3: 4from node 1 to node 4: 4
8. Sort a given set of elements using Quick sort 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.
#include<stdio.h>
#include<conio.h>
#include<time.h>#define m1 1000
#define n1 10000
int a[20];
void main()
{int i,n,j;
clock_t start,end;
clrscr();
printf("Enter the value of n:");scanf("%d",&n);
printf("Enter the array elements:");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}start=clock();
for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
quicksort(0,n-1);
Gogte Institute of Technology Department of MCA 24
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 25/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
end=clock();
printf("The sorted array is:");
for(i=0;i<n;i++){
printf("%d\t",a[i]);
} printf("\n\nTime=%f",(end-start)/(CLK_TCK));
getch();
}quicksort(int low,int high)
{
int mid;
if(low<high){
mid=part(low,high);
quicksort(low,mid-1);
quicksort(mid+1,high);}
}int part(int low,int high)
{
int pivot,i,j,temp;
pivot=a[low];i=low;
j=high;
while(a[i]<pivot && i<high){
++i;
}while(a[j]>pivot && j>0)
{
--j;}
if(i<j)
{
temp=a[i];a[i]=a[j];
a[j]=temp;
}else
{
temp=a[j];a[j]=a[low];
a[low]=temp;
}
return(j);
Gogte Institute of Technology Department of MCA 25
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 26/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
}
Output
Enter the value of n:10
Enter the array elements:2 1 4 56 8 7 9 90 65 45The sorted array is:1 2 4 7 8 9 45 56
65 90
Time=6.318681
Enter the value of n:5
Enter the array elements:12 11 78 98 56The sorted array is:11 12 56 78 98
Time=2.362637
Enter the value of n:15
Enter the array elements:15 14 13 12 11 10 9 8 7 6 5 4 3 2 1The sorted array is:1 2 3 4 5 6 7 8
9 10 11 12 13 14 15
Time=10.714286
Enter the value of n:20
Enter the array elements:20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1The sorted array is:1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17 18
19 20
Time=15.604396
Graph
Quick Sort
n time
5 2.362
10 6.318
15 10.714
20 15.604
Gogte Institute of Technology Department of MCA 26
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 27/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Graph of Quick Sort
0
2
4
6
8
10
12
14
16
18
0 5 10 15 20 25
n
t i m e
time
9. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal’salgorithm.
#include<conio.h>#include<stdio.h>
struct tag
{int v1,v2,wt;
};
typedef struct tag edge;
void readgraph(edge e[],int n)
{int k;
for(k=1;k<=n;k++){
printf("\nInput edge<v1,v2,wt>:\n");
scanf("%d%d%d",&e[k].v1,&e[k].v2,&e[k].wt);}
}
void printgraph(edge e[],int n){
int k;
for(k=1;k<=n;k++) printf("\n%d<...>%d: %d\n",e[k].v1,e[k].v2,e[k].wt);}
int find(int p[],int k)
{if(p[k]==k)
return k;
else
Gogte Institute of Technology Department of MCA 27
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 28/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
return(find(p,p[k]));
}
void bsort(edge e[],int n){
int i,j;
edge temp;for(i=1;i<=n;i++)
for(j=1;j<=n-1;j++)
if(e[j].wt>e[j+1].wt){
temp=e[j];
e[j]=e[j+1];
e[j+1]=temp;}
}
int min(int x,int y)
{return((x<y)?x:y);
}int max(int x,int y)
{
return((x>y)?x:y);
}int kruskal(edge e1[],int n1, edge e2[], int n2)
{
int mincost=0,parent[30];int i,k,j,p1,p2,mn,mx;
int v1,v2,wt,n;
for(k=1;k<=n2;k++) parent[k]=k;
bsort(e1,n1);
for(i=1,j=1;(i<=n1)&&(j<=n2);i++,j++){
v1=e1[i].v1;
v2=e1[i].v2;
wt=e1[i].wt; p1=find(parent,v1);
p2=find(parent,v2);
if(p1==p2) j=j-1;
else
{e2[j]=e1[i];
mn=min(p1,p2);
mx=max(p1,p2);
parent[mx]=mn;
Gogte Institute of Technology Department of MCA 28
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 29/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
mincost=mincost+wt;
}
}return(mincost);
}
void main(){
edge e1[30],e2[30];
int n1,n2,n,cost;clrscr();
printf("\nEnter how many nodes:\n");
scanf("%d",&n);
n2=n-1; printf("\nEnter how many edges of the graph:\n");
scanf("%d",&n1);
readgraph(e1,n1);
cost=kruskal(e1,n1,e2,n2); printf("\nMinimum cost=%d\n",cost);
printf("\nThe spanning tree is:\n"); printgraph(e1,n2);
getch();
}
Output
Enter how many nodes:4
Enter how many edges of the graph:4
Input edge<v1,v2,wt>:
1 2 3
Input edge<v1,v2,wt>:
2 3 4
Input edge<v1,v2,wt>:
3 4 5
Input edge<v1,v2,wt>:
1 4 6
Minimum cost=12
The spanning tree is:
1<...>2: 3
Gogte Institute of Technology Department of MCA 29
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 30/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
2<...>3: 4
3<...>4: 5
10. 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.
BFS
#include <stdio.h>#include <process.h>
void bfs(int a[20][20], int n,int source,int t[20][2], int s[])
{ int f,r,q[20]; /* for queue operations*/
int u,v; /* represent two vertices */int k = 0; /* To store the result pair (u, v)*/
int i; /* index variable*/
for (i = 1; i <= n; i++){
s[i] = 0; /* No node is visited in the beginning*/
}
f = r = k = 0; /* Queue is empty*/
q[r] = source; /* Insert source vertex into queue*/
s[source] = 1; /* Add source to S (indicates source is visited)*/
while ( f <= r ) /* As long as queue is not empty*/
{
u = q[f++]; /* Delete the next vertex to be
explored from q*/
for ( v = 1; v <= n; v++)
{/* Find the nodes v which are adjacent to u*/
if ( a[u][v] == 1 && s[v] == 0 ){
s[v] = 1; /* add
v to s indicates that v is visited now*/
Gogte Institute of Technology Department of MCA 30
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 31/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
q[++r] = v; /*
Insert new vertex into Q for exploration*/
t[k][0] = u; /*Output the
pair (u, v)edge reachable from u to v stored*/
t[k][1] = v;k++;
}
}}
}
void main()
{
int n,i,j,source,a[20][20],t[20][2],flag;
int s[20]; /* To insert the vertices which are visited*/clrscr();
printf("Enter the no. of nodes\n");
scanf("%d",&n);
printf("Enter the adjacency matrix\n");for ( i = 0; i < n; i++)
{
for ( j = 0; j < n; j++){
scanf("%d",&a[i][j]);
}}
printf("Enter the source\n");scanf("%d",&source);
bfs(a, n,source,t, s);
flag = 0; /* All nodes are reachable*/
for( i = 0; i < n; i++){
if ( s[i] == 0 )
{ printf("vertex %d is not reachable\n",i);
flag = 1; /* A vertex is not reachable*/
}
else
Gogte Institute of Technology Department of MCA 31
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 32/54
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 33/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
DFS
#include <stdio.h>#include <process.h>
void dfs(int n, int cost[10][10],int u,int t[10][10],int s[]){
int v;
static int k = 1;
s[u] = 1;
for ( v = 1; v <= n; v++){
if ( cost[u][v] == 1 && s[v] == 0 )
{
t[k][1] = u;t[k][2] = v;
k++;dfs(n,cost,v,t,s);
}
}
}
void main()
{
int n,i,j,source,cost[10][10],s[10],t[10][10];
clrscr();printf("Enter the no. of nodes\n");
scanf("%d",&n);
printf("Enter the cost adjacency matrix\n");for ( i = 1; i <= n; i++)
{
for ( j = 1; j <= n; j++)
{scanf("%d",&cost[i][j]);
}
}printf("Enter the source\n");
scanf("%d",&source);
for ( i = 1; i <= n; i++)
{
s[i] = 0;
}
Gogte Institute of Technology Department of MCA 33
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 34/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
dfs(n,cost,source,t,s);
for ( i = 1; i <= n; i++)
{
if ( s[i] == 1 )printf("%d is reachable\n",i);
else
printf("%d is not reachable\n",i);}
for( i = 1; i <= n; i++)
{if ( s[i] == 0 )
{
printf("Graph is not connected\n");
exit(0);}
}printf("Graph is connected\n");
printf("The spanning tree is shown below\n");
for ( i = 1; i <= n-1; i++){
printf("%d %d\n",t[i][1],t[i][2]);
}getch();
}
Output
Enter the no. of nodes2
Enter the cost adjacency matrix
1 1
1 1Enter the source
0
1 is not reachable2 is not reachable
Graph is not connected
Enter the no. of nodes
3
Enter the cost adjacency matrix
1 0 1
Gogte Institute of Technology Department of MCA 34
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 35/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
1 0 1
1 1 0
Enter the source1
1 is reachable
2 is reachable3 is reachable
Graph is connected
The spanning tree is shown below1 3
3 2
11. Find a subset of a given set S= {s1, s2, Sn} of n positive integers whose sum is equalto 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.
#include<stdio.h>
#include<conio.h>#define m 30
void subset(int n,int d,int s[]);
void main()
{
int i,n,d,s[m];clrscr();
printf("\nEnter number of elements : ");
scanf("%d",&n); printf("\nEnter the set in increasing order\n");
for(i=0;i<n;i++)
scanf("%d",&s[i]); printf("\nEnter the sum of subset d = ");
scanf("%d",&d);
subset(n,d,s);
getch();}
void subset(int n,int d,int s[]){
int i,k,sum=0,selected[m],found=0;
for(i=0;i<n;i++)selected[i]=0;
k=0;
selected[k]=1;
Gogte Institute of Technology Department of MCA 35
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 36/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
while(1)
{
if(k<n && selected[k]==1){
if(sum+s[k]==d)
{ found=1;
printf("\n\nSolution is : \n\n");
for(i=0;i<n;i++){
if(selected[i]==1)
printf("%d\t",s[i]);
}selected[k]=0;
}
else if(sum+s[k]<d)
sum+=s[k];else
selected[k]=0;}
else
{
k--;while(k>=0 && selected[k]==0)
{
k--;}
if(k<0)
break;selected[k]=0;
sum-=s[k];
}k++;
selected[k]=1;
}
if(!found) printf("\nSolution does not exist");
}
Output
Enter number of elements : 5
Enter the set in increasing order
1 2 5 6 8
Gogte Institute of Technology Department of MCA 36
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 37/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Enter the sum of subset d = 9
Solution is :
1 2 6
Solution is :
1 8
12. a. Implement Horspool algorithm for String Matching.
b. Find the Binomial Co-efficient using Dynamic Programming.
Horspool Algorithm
#include <stdio.h>#include <string.h>
#include <process.h>
/* Function to obtain the shift table for the characters in text string */
void shift_table(char p[], int t[])
{int i,m;
/* Length of pattern string */m = strlen(p);
/* Initialize the table with pattern length */for (i = 0; i < 128; i++) t[i] = m;
/*Find the distance of first m-1 characters of string from the last character*/for (i = 0; i <= m-2; i++)
{
t[p[i]]= m - 1 - i;
}}
int horspool_pattern_match(char p[], char s[]){
int m, n, i, k, t[128];
shift_table(p, t); /* Obtain the shifs required when mismatch occur */
m = strlen(p); /* Compute the length of pattern string */
n = strlen(s); /* Compute the length of text string */
Gogte Institute of Technology Department of MCA 37
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 38/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
i = m - 1; /* Position of pattern string's right end */
while ( i < n ) /* Repeat till the end of text string */{
k = 0;
while ( k < m && p[m-1-k] == s[i-k] ){
k = k + 1; /* Matching of pattern and text string in progress */
}
/* Pattern found ? */
if ( k == m ) return i - m + 1;
/* No match, so shift the pattern towards right */
i = i + t[s[i]];
}
return -1;
}
void main()
{
char p[20], s[40];int pos;
clrscr();
printf("Enter the text string\n");
gets(s);
printf("Enter the pattern string\n");
gets(p);
pos = horspool_pattern_match(p, s);
if ( pos == -1)
{ printf("Pattern string not found\n");
exit(0);
}
printf("Pattern string found at %d position\n",pos + 1);
getch();}
Gogte Institute of Technology Department of MCA 38
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 39/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Output
Enter the text stringcomputer algorithm
Enter the pattern string
goriPattern string found at 12 position
Enter the text stringvery good moring
Enter the pattern string
bad
Pattern string not found
Dynamic Programming
//Binomial coefficient#include<stdio.h>
#include<conio.h>#define MAX 30
int binomial(int n,int k);
main()
{
int n,k;clrscr();
printf("Enter the value of n and k:");
scanf("%d%d",&n,&k); printf("\nThe binomial coefficient c(n,k),=%d",binomail(n,k));
getch();
return 0;}
int binomail(int n,int k)
{
int i,j,c[MAX][MAX],min;for(i=0;i<=n;i++)
{
printf("\n");min=i<k ? i:k;
for(j=0;j<=min;j++)
{if(j==0 || i==j)
c[i][j]=1;
else
c[i][j]=c[i-1][j-1]+c[i-1][j];
Gogte Institute of Technology Department of MCA 39
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 40/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
printf("%5d",c[i][j]);
}
}return(c[n][k]);
}
Output
Enter the value of n and k:2 1
1
1 1
1 2The binomial coefficient c(n,k),=2
Enter the value of n and k:3 4
1
1 11 2 1
1 3 3 1
The binomial coefficient c(n,k),=0
13. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm.
/*prims algorith*/
#include<stdio.h>
#include<process.h>#include<stdlib.h>
#define MAX 6
#define INFINITY 1000
void prim(int [][MAX],int);
int edge[MAX][2];
void main()
{
int cost[MAX][MAX],n,mincost,i,j;clrscr();
mincost=0;
printf("\nEnter the nos of vertices:\n");scanf("%d",&n);
printf("\nEnter cost adjacency matrix:\n");
printf("(Enter 1000 to indicate no edge)\n");
for(i=1;i<=n;i++)
Gogte Institute of Technology Department of MCA 40
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 41/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
{
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);}
prim(cost,n);
printf("\n");for(i=1;i<=n-1;i++)
mincost+=cost[edge[i][1]][edge[i][2]];
printf("\nThe solution to MWST=%d\n",mincost);if(mincost>=1000)
{
printf("There is no minimum spanning tree.\n");
exit(1);}printf("\nEdge of the minimum spanning tree:\n");
for(i=1;i<=n-1;i++)
printf("<%2d,%2d>",edge[i][1],edge[i][2]);
getch();}
void prim(int cost[][MAX],int n){
int closest[MAX],lowcost[MAX],min,i,j,k;
for(i=2;i<=n;i++)
{lowcost[i]=cost[1][i];
closest[i]=1;
}for(i=2;i<=n;i++)
{
min=lowcost[2];k=2;
for(j=3;j<=n;j++)
if(lowcost[j]<min){
min=lowcost[j];
k=j;
}edge[i-1][1]=closest[k];
edge[i-1][2]=k;
lowcost[k]=INFINITY;
for(j=2;j<=n;j++)if(cost[k][j]<lowcost[j])
if(lowcost[j]<INFINITY)
{
lowcost[j]=cost[k][j];
Gogte Institute of Technology Department of MCA 41
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 42/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
closest[j]=k;
}
}}
Output
Enter the nos of vertices:2
Enter cost adjacency matrix:
(Enter 1000 to indicate no edge)1000 1
1 1000
The solution to MWST=1
Edge of the minimum spanning tree:
< 1, 2>
Enter the nos of vertices:
3
Enter cost adjacency matrix:
(Enter 1000 to indicate no edge)
1000 1 11 1000 1
1000 1000 1
The solution to MWST=2
Edge of the minimum spanning tree:< 1, 2>< 1, 3>
14. a. Implement Floyd’s algorithm for the All-Pairs-Shortest-Paths problem.b.Compute the transitive closure of a given directed graph using Warshall’s
algorithm.
Warshall’s Algorithm
#include<stdio.h>
#include<conio.h>
Gogte Institute of Technology Department of MCA 42
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 43/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
int i,j,k,n;
int a[10][10];
void warshall(){
for(k=1;k<=n;k++)
{for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++){
a[i][j]=a[i][j]||(a[i][k]&&a[k][j]);
}
}}
}
void main(){
clrscr(); printf("\n Enter the no of vertices;");
scanf("\n %d",&n);
printf("\n Enter the matrix:");
for(i=1;i<=n;i++){
for(j=1;j<=n;j++)
{scanf("\t%d",&a[i][j]);
}
printf("\n");}
warshall();
printf("\n The closure matrix is:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++){
printf("\t%d",a[i][j]);
} printf("\n");
}
getch();}
Output
Gogte Institute of Technology Department of MCA 43
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 44/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Enter the no of vertices;4
Enter the matrix:0 1 0 0
0 0 1 0
0 0 0 1
1 0 0 0
The closure matrix is:1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1
15. Implement N Queen’s problem using Back Tracking.
#include <stdio.h>
#include <math.h>#include<conio.h>
#include<process.h>
int board[2];
int count;
void main(){
int n,i,j;
void queen(int row, int n);clrscr();
printf("\nProgram for n-Queen's Using Backtracking");
printf("\nEnter Number of Queen's");
scanf("%d",&n);Queen(1,n);/*trace using backtrack*/
getch();
}/*This function is for printing the solution to n-Queen's problem*/
void print_board(int n)
{int i,j;
printf("\nSolution %d:\n",++count);
/*number of solution*/
for(i=1;i<=n;i++)
Gogte Institute of Technology Department of MCA 44
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 45/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
{
printf("\t%d",i);
}for(i=1;i<=n;i++)
{
printf("\n%d",i);for(j=1;j<=n;j++)
{
if(board[i]==j)printf("\tQ");/*Queen at i,j position*/
else
printf("\t-");/*empty slot*/
}}
printf("\nPress any key to continue");
getch();
}/*This function is for checking for the conflicts. If there is no conflict
for the desired position it returns 1 otherwise it returns 0*/int place(int row, int column)
{
int i;
for(i=1;i<=row;i++){
if(board[i]==column)
return 0;else
if(abs(board[i]-column)==abs(i-row))
return 0;}
/*no conflicts hence Queen can be placed*/
return 1;}
/*By this function we try the next free slot and check for proper positioning
of queen*/
Queen(int row, int n){
int column;
for(column=1;column<=n;column++){
if(place(row,column))
{board[row]=column;/*no conflict to place Queen*/
if(row==n)
print_board(n);/*printing the board configuration*/
else
Gogte Institute of Technology Department of MCA 45
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 46/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Queen(row+1,n);/*try next queen with next position*/
}
}}
Output
Program for n-Queen's Using Backtracking
Enter Number of Queen's5
Solution 1:
1 2 3 4 5
1 Q - - - -2 - - Q - -
3 - - - - Q
4 - Q - - -
5 - - - Q -Press any key to continue
Solution 2:1 2 3 4 5
1 Q - - - -
2 - - - Q -
3 - Q - - -4 - - - - Q
5 - - Q - -
Press any key to continue
Gogte Institute of Technology Department of MCA 46
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 47/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Gogte Institute of Technology Department of MCA 47
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 48/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Gogte Institute of Technology Department of MCA 48
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 49/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Gogte Institute of Technology Department of MCA 49
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 50/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Gogte Institute of Technology Department of MCA 50
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 51/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Gogte Institute of Technology Department of MCA 51
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 52/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Gogte Institute of Technology Department of MCA 52
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 53/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL
Gogte Institute of Technology Department of MCA 53
8/8/2019 Algorithms Laboratory
http://slidepdf.com/reader/full/algorithms-laboratory 54/54
ALGORITHMS LABORATORY (07MCA48) LAB MANUAL