Ada Lab Manual
Ada Lab Manual
Page | 1
Channabasaveshwara Institute of Technology
(Affiliated to VTU, Belgaum & Approved by
AICTE, New Delhi) (NAAC Accredited &
ISO 9001:2015 Certified Institution)
NH 206 (B.H. Road), Gubbi, Tumkur – 572 216. Karnataka.
Analysis & Design of Algorithms Lab Semester 4
Course Code BCSL404 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 0:0:2:0 SEE Marks 50
Credits 01 Exam Hours 2
Examination type (SEE) Practical
Course objectives:
● To design and implement various algorithms in C/C++ programming using suitable development tools to address different
computational challenges.
● To apply diverse design strategies for effective problem-solving.
● To Measure and compare the performance of different algorithms to determine their efficiency and suitability for specific tasks.
Sl.No Experiments
1 Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Kruskal's algorithm.
2 Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Prim's algorithm.
3 a. Design and implement C/C++ Program to solve All-Pairs Shortest Paths problem using Floyd's algorithm.
b. Design and implement C/C++ Program to find the transitive closure using Warshal's
algorithm.
4 Design and implement C/C++ Program to find shortest paths from a given vertex in a weighted
connected graph to other vertices using Dijkstra's algorithm.
5 Design and implement C/C++ Program to obtain the Topological ordering of vertices in a given
digraph.
6 Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic
Programming method.
7 Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack
problems using greedy approximation method.
8 Design and implement C/C++ Program to 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.
9 Design and implement C/C++ Program to sort a given set of n integer elements using Selection Sort method and
compute its time complexity. Run the program for varied values of n> 5000 and record the time taken to sort. 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.
10 Design and implement C/C++ Program to sort a given set of n integer elements using Quick Sort method and
compute its time complexity. Run the program for varied values of n> 5000 and record the time taken to sort.
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.
Page | 2
11 Design and implement C/C++ Program to sort a given set of n integer elements using Merge Sort method
and compute its time complexity. Run the program for varied values of n> 5000, and record the time taken
to sort. 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.
12 Design and implement C/C++ Program for N Queen's problem using Backtracking.
Page | 3
BCSL404-Algorithms Lab IV Sem ISE
● SEE shall be conducted jointly by the two examiners of the same institute, examiners are appointed by the Head of
the Institute.
● The examination schedule and names of examiners are informed to the university before the conduction of the
examination. These practical examinations are to be conducted between the schedule mentioned in the academic
calendar of the University.
● All laboratory experiments are to be included for practical examination.
● (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer script to be strictly
adhered to by the examiners. OR based on the course requirement evaluation rubrics shall be decided jointly by
examiners.
● Students can pick one question (experiment) from the questions lot prepared by the examiners jointly.
● Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by examiners.
General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure and result in -60%, Viva-
voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marks and scored marks shall be scaled
down to 50 marks (however, based on course type, rubrics shall be decided by the examiners)
Change of experiment is allowed only once and 15% of Marks allotted to the procedure part are to be made zero.
The minimum duration of SEE is 02 hours
CONTENT SHEET
10. Design and implement C/C++ Program to sort a given set of n integer elements
using Quick Sort method and compute its time complexity. Run the program for
varied values of n> 5000 and record the time taken to sort. 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.
11. Design and implement C/C++ Program to sort a given set of n integer elements
using Merge Sort method and compute its time complexity. Run the program
for varied values of n> 5000, and record the time taken to sort. 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.
12.
Design and implement C/C++ Program for N Queen's problem using Backtracking.
Analysis framework:
The efficiency of the algorithm depends on two factors:
Space efficiency
Time efficiency
Space efficiency: The space efficiency of an algorithm is the amount of memory required to
run program completely and efficiently.
Components that affect space efficiency:
Program space
Data space
Stack space
Time efficiency: The Time efficiency of an algorithm is measured purely on how fast a given
algorithm is executed. Since the efficiency of an algorithm is measured using time, the word
time complexity is often associated with an algorithm.
Components that affect space efficiency:
Speed of the computer
Choice of the programming language
Compiler used
Choice of the algorithm
Number of inputs/outputs
Size of inputs/outputs
While N! =0 do
RM%N //compute the remainder
MN //Assign N to M
N R // Assign remainder to N
End while
Return M //Return the GCD
Model development
Design an algorithm
Program testing
Parallel Programming:
In parallel programming, the processing is broken up into parts, each of which can be
executed concurrently. The instructions from each part run simultaneously on different CPUs.
These CPUs can exist on a single machine, or they can be CPUs in a set of computers
connected via a network.
It is possible to write parallel programming for multiprocessors using MPI and
OpenMP
OpenMP:
OpenMp is an application programming interface (API) for parallel programming on
multiprocessors
It consists of a set of compiler directives and a library of support functions
OpenMp works in conjunction with Standard Fortran, C or C++
Design of Algorithm:
Algorithm: (Pseudo Code)
SelectionSort(A[0…n-1])
//sort a given array by select5ion sort
//input:A[0…n-1]of orderable elements
Output:Array a[0…n-1] Sorted in ascending order
for i<- 0 to n-2 do
min<-i
for j<-i+1 to n-1 do
if A[j]<A[min] min<-j
swap A[i] and A[min]
Code: (Implementation)
#include<stdio.h>
#include<unistd.h>
#include<time.h>
void selsort(int a[],int n)
{
int i,j,small,pos,temp;
for(j=0;j<n-1;j++)
{
small=a[j];
pos=j;
for(i=j+1;i<n;i++)
{
if(a[i]<small)
{
small=a[i];
pos=i;
}
}
temp=a[j];
a[j]=small;
a[pos]=temp;
}
}
int main()
{
int a[100],i,n;
clock_t start,end;
float dura;
printf(" To sort the Integer elements using Selection Sort Method\n\n");
printf("\nEnter the Number of elements to be sorted which is less than the array size
50\n");
scanf("%d",&n);
dura=(end-start)/CLOCK_PER_SEC;
printf("\nTime taken is:%f",dura);
printf("\nSorted array is:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
Design of Algorithm:
Algorithm: (Pseudo Code)
Quick Sort:
ALGORITHM Quicksort (A[l….r])
//Sorts a subarray by quicksort
//Input: A subarray A[l…r] of A[0…n-1], defined by its left & right indices l & r
//Output: Subarray A[l…r] sorted in increasing order
if l < r
s Partition (A[l…r]) // s is a split position
Quicksort ( A[l….s-1] )
Quicksort (A[s+1…r])
Code: (Implementation)
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
int ct,sw;
void quicksort(int a[],int low,int high)
{
int s;
//To check for boundary condition
if(low<high)
{
s=partition(a,low,high);
quicksort(a,low,s-1);
quicksort(a,s+1,high);
}
}
int partition(int a[],int low,int high)
{
int p,i,j,temp;
p=a[low];
i=low+1;
j=high;
while(1)
{
while(a[i]<=p && i<high)
i++,ct++; // count for the comparision
while(a[j]>p)
j--,ct++; // count for the comparision
if(i<j)
{
sw++; // count for the swap
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else
{
sw++; // count for the swap
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;
}
}
}
int main()
{
int a[5000],i,n;
printf(" To sort the Integer elements using Quick Sort Method\n\n");
printf("\nEnter the Number of elements to be sorted which is less than
the array size5000\n");
scanf("%d",&n);
if(n>0 && n<=5000) // array bound check
{
for(i=0;i<n;i++)
{
a[i] = rand()%1000;
}
}
else
{
printf("Invalid input.. please try again...\n");
return -1;
}
printf("The Inputs generated by Random Number Generated are \n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
quicksort(a,0,n-1);
printf("\n Sorted Integer Array \n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf(" \nThe number of Comparisions are : %d units",ct);
printf(" \nThe number of Swaps are : %d units",sw);
return 0;
}
Algorithm:(Pseudo Code)
Merge Sort:
ALGORITHM Mergesort (A [0...n-1])
//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 increasing order
if n>1
Copy A[0..[n/2]-1] to B[0…[n/2]-1]
Copy A[0..[n/2]-1] to C[0…[n/2]-1]
Mergesort (B[0…[n/2]-1)
Mergesort (C[0…[n/2]-1)
Merge(B,C,A)
i 0; j0 ; k0
while i<p and j<q do
if B[i] ≤ C[j]
A[k]B[i] ; i i+1
else A[k]C[j] ; j j+1
k k+1
if i=p
copy C[j…q-1] to A[k…p+q-1]
else copy B[i…p-1] to A[k…p+q-1]
Code: (Implementation)
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
#include<time.h>
void main()
{
int a[200],i,n;
double startTime,endTime;
printf("=========== Parallelized Merge Sort ==========\n");
printf("Enter the number of elements\n");
scanf("%d",&n);
randomize();
for(i=0;i<n;i++)
{
a[i]=random(1000);
}
j++;
k++;
}
}
while(i<=mid)
c[k++]=a[i++];
while(j<=high)
c[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=c[i];
}
void merge_sort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
#pragma omp parallel sections
{
#pragma omp section
merge_sort(a,low,mid);
#pragma omp section
merge_sort(a,mid+1,high);
}
simple_merge(a,low,mid,high);
}
}
Knapsack problem:
(Combinatory Problem)
Aim:
To Implement 0/1 Knapsack problem using dynamic programming.
Problem Statement:
We are given n objects and a knapsack. Each object has a weight, w and the
maximum weight or capacity of the knapsack is M. Each object is associated with a value or
profit is carried when it is places in the knapsack.
Objective:
We must fill the knapsack which maximizes the profit control and the output is subset
of object number.
Algorithm:(Pseudo Code)
Algorithm Knapsack(i,j)
If j<weights[i]
Value= Knapsack(i-1,j)
Else
Value=max(knapsack(i-1,j),vaues[i]+ knapsack(i-1,j-weights[i]))
V[I,j]=value
Return v[i,j]
Code: (Implementation)
#include<stdio.h>
#define INF 999
#define MAX 100
int p[MAX],c[MAX][MAX],t[MAX][2];
int find(int v)
{
while(p[v])
v=p[v];
return v;
}
void union1(int i,int j)
{
p[j]=i;
}
void kruskal(int n)
{
int i,j,k,u,v,min,res1,res2,sum=0;
for(k=1;k<n;k++)
{
min=INF;
for(i=1;i<n-1;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)continue;
if(c[i][j]<min)
{
u=find(i);
v=find(j);
if(u!=v)
{
res1=i;
res2=j;
min=c[i][j];
}
}
}
}
union1(res1,find(res2));
t[k][1]=res1;
t[k][2]=res2;
sum=sum+min;
}
printf("\nCost of spanning tree is=%d",sum);
printf("\nEdgesof spanning tree are:\n");
for(i=1;i<n;i++)
printf("%d -> %d\n",t[i][1],t[i][2]);
}
int main()
{
int i,j,n;
printf("\nEnter the n value:");
scanf("%d",&n);
for(i=1;i<=n;i++)
p[i]=0;
printf("\nEnter the graph data:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
kruskal(n);
return 0;
}
Algorithm:
ALGORITHM prim(G)
// Prim’s Algorithm for constructing a minimum spanning tree
//Input: A weighted connected graph G=(V,E)
//Output: ET , the set of edges composing a minimum spanning tree of G
VT <-- {V0}
ET <-- Ø
for i <-- 1 to |V| − 1 do
find a minimum-weight edge e* = (v*, u*) among all the edges (v,u)
such that v is in VT and u is in V − VT
VT <-- VT U {u*}
ET <-- ET U {e*}
return ET
Code: (Implementation)
#include<stdio.h>
#define INF 999
int prim(int c[10][10],int n,int s)
{
int v[10],i,j,sum=0,ver[10],d[10],min,u;
for(i=1;i<=n;i++)
{
ver[i]=s;
d[i]=c[s][i];
v[i]=0;
}
v[s]=1;
for(i=1;i<=n-1;i++)
{
min=INF;
for(j=1;j<=n;j++)
if(v[j]==0 && d[j]<min)
{
min=d[j];
u=j;
}
v[u]=1;
sum=sum+d[u];
printf("\n%d -> %d sum=%d",ver[u],u,sum);
for(j=1;j<=n;j++)
if(v[j]==0 && c[u][j]<d[j])
{
d[j]=c[u][j];
ver[j]=u;
}
}
return sum;
}
void main()
{
int c[10][10],i,j,res,s,n;
printf("Prims Algorithm");
printf("\nEnter the number of nodes");
scanf("%d",&n);
printf("\nEnter the %d*%d matrix:\n",n,n);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
printf("\nEnter the souce node:");
scanf("%d",&s);
res=prim(c,n,s);
printf("\nCost of minimum spanning tree is=%d",res);
}
Aim:
Implement All-Pairs Shortest Paths Problem using Floyd's algorithm.
Parallelize this algorithm, implement it using OpenMP and determine the speed-
up achieved
Algorithm:
ALGORITHM Floyd (W [1…n, 1…n])
// Implements Floyd’s algorithm for all-pair shortest-paths problem
//Input: The weight matrix W of a graph with no negative-length cycle
//Output: The distance matrix of the shortest paths’ lengths D W is not
//necessary if W can be overwritten
for k 1 to n do
for i 1 to n do
for j 1 to n do
D[i,j] min { D[i,j], D[i,k] + D[k,j] }
return D
Code: (Implementation)
#include<stdio.h>
#include<omp.h
int min(int a,int b)
{
return a<b?a:b;
}
void floyd(int w[10][10],int n)
{
int i,j,k;
startTime=omp_get_wtime();
floyd(a,n);
endTime = omp_get_wtime();
Algorithm:
ALGORITHM Warshall’s (A[1..n,1..n])
//Implements Warshall’s Algorithm to compute the transitive closure
//Input: The adjacency matrix A of a directed graph with n vertices
//Output: The transitive closure of the digraph
R(0) <-A
For k<- 1 to n do
For i<-1 to n do
For j<- 1 to n do
R(k) [ i,j]<- R(k-1) [ i,j] or R(k-1) [ i,k] and R(k-1) [ k,j]
Return R(n)
Code:
#include<stdio.h>
#include<stdlib.h>
void warshalls(int a[20][20], int n)
{
int i,j,k;
for (k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
a[i][j] = a[i][j] || a[i][k] && a[k][j];
printf("\n The transitive closure is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
}
void main()
{
int a[20][20],n,i,j;
printf(" Compute transitive closure using Warshalls Algorithm \n");
printf("\n Enter the number of vertices of the graph:\n");
scanf("%d",&n);
if(n>0 && n <90)
{
printf("\n Enter the adjacency matrix:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
warshalls(a,n);
}
else
{
printf("Enter the valid number of vertices\n");
}
}
Aim:
To find shortest paths from a given starting vertex to other vertices in a
weighted connected graph using Dijkstra's algorithm.
Code:
#include<stdio.h>
#define INF 999
void dijkstra(int c[10][10],int n,int s,int d[10])
{
int v[10],min,u,i,j;
for(i=1;i<=n;i++)
{
d[i]=c[s][i];
v[i]=0;
}
v[s]=1;
for(i=1;i<=n;i++)
{
min=INF;
for(j=1;j<=n;j++)
if(v[j]==0 && d[j]<min)
{
min=d[j];
u=j;
}
v[u]=1;
for(j=1;j<=n;j++)
if(v[j]==0 && (d[u]+c[u][j])<d[j])
d[j]=d[u]+c[u][j];
}
}
int main()
{
int c[10][10],d[10],i,j,s,sum,n;
printf("\nEnter the number of vertices of graph:");
scanf("%d",&n);
printf("\nEnter the weights of the edges of the graph\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
printf("\nEnter the souce vertex to find shorest path:");
scanf("%d",&s);
dijkstra(c,n,s,d);
for(i=1;i<=n;i++)
printf("\nShortest distance from %d to %d is %d",s,i,d[i]);
return 0;
Topological Ordering
(Sorting Problem)
Step 3: Push all the nodes which is having the indegree zero
Step 4: Pop the element from the stack and delete all the edges outgoing from the deleted
node
Step 5: If the indegree of the node is zero, push that node to the stack.
Step 7: Stop
Code:
#include<stdio.h>
int temp[10],k=0;
void sort(int a[][10],int id[],int n)
{
int i,j;
for(i=1;i<=n;i++)
{
if(id[i]==0)
{
id[i]=-1;
temp[++k]=i;
for(j=1;j<=n;j++)
{
if(a[i][j]==1 && id[j]!=-1)
id[j]--;
}
i=0;
}
}
}
void main()
{
int a[10][10],id[10],n,i,j;
printf("\nEnter the vertices of the graph:");
scanf("%d",&n);
for(i=1;i<=n;i++)
id[i]=0;
printf("\nEnter the matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
if(a[i][j]==1)
id[j]++;
}
}
sort(a,id,n);
if(k!=n)
printf("\nTopological ordering not possible");
else
{
printf("\nTopological ordering is:");
for(i=1;i<=k;i++)
printf("%d ",temp[i]);
}
}
Aim:
To Implement 0/1 Knapsack problem using dynamic programming.
Problem Statement:
We are given n objects and a knapsack. Each object has a weight, w and the
maximum weight or capacity of the knapsack is M. Each object is associated with a value or
profit is carried when it is places in the knapsack.
Objective:
We must fill the knapsack which maximizes the profit control and the output is subset
of object number.
Algorithm:(Pseudo Code)
Algorithm Knapsack(i,j)
If j<weights[i]
Value= Knapsack(i-1,j)
Else
Value=max(knapsack(i-1,j),vaues[i]+ knapsack(i-1,j-weights[i]))
V[I,j]=value
Return v[i,j]
Code:
#include <stdio.h>
#include <stdlib.h>
int w[10], v[10], a[10][10], t[10];
int c, i, n, j;
int max(int a, int b)
{
return (a > b) ? a : b;
}
void knapsack(int c, int n)
{
int i, j;
for (i = 0; i <= n; i++)
{
for (j = 0; j <= c; j++)
{
if (i == 0 || j == 0)
a[i][j] = 0;
else if (w[i] > j)
a[i][j] = a[i - 1][j];
else
a[i][j] = max(a[i - 1][j], (a[i - 1][j - w[i]] + v[i]));
}
}
i = n;
j = c;
while (i > 0 && j > 0)
{
if (a[i][j] != a[i - 1][j])
{
t[i] = 1;
j = j - w[i];
}
i--;
}
}
void read_capacity()
{
printf("\n\n Enter the capacity of the knapsort:");
scanf("%d", &c);
if (c > 0)
read_numofitems();
else
{
printf("\n\n Invalid capacity, please try again...");
read_capacity();
}
}
int read_numofitems()
{
printf("\n\n Enter the number of items:\n");
scanf("%d", &n);
if (n > 0)
read_weights();
else
{
printf("\n\n Invalid items, please try again...");
read_numofitems();
}
return 1;
}
int read_weights()
{
printf("\n\n Enter the corresponding weights:\n");
for (i = 1; i <= n; i++)
scanf("%d", &w[i]);
for (i = 1; i <= n; i++)
{
if (w[i] > 0 && w[i] <= 999)
{
// Valid weight, continue to read values
}
else
{
printf("\n\n Invalid weights, please try again..");
read_weights();
}
}
read_values();
return 0;
}
int read_values()
{
printf("\n\n Enter the corresponding values:\n");
for (i = 1; i <= n; i++)
scanf("%d", &v[i]);
for (i = 1; i <= n; i++)
{
if (v[i] > 0 && v[i] <= 999)
{
// Valid value, continue to knapsack
}
else
{
printf("\n\n Invalid values, please try again...");
read_values();
}
}
knapsack(c, n);
return 0;
}
int main()
{
printf("\t\t **THIS PROGRAM DEMONSTRATES KNAPSACK PROBLEM**");
read_capacity();
printf("\n\n Resultant matrix is:\n");
for (i = 0; i <= n; i++)
{
for (j = 0; j <= c; j++)
printf("\t%d", a[i][j]);
printf("\n");
}
printf("\n\n The optimal solution is: %d", a[n][c]);
printf("\n\n Items selected are:\n");
for (i = 1; i <= n; i++)
if (t[i] == 1)
printf("\t%d", i);
return 0;
}
10) Design and implement C/C++ Program to 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.
Aim:
To 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}.
Algorithm:
Step 1: Start
Step 2: Find the subset for given set
Step 3: Add the elements of the subset
Step 4: If the sum of the subset is equal to the given positive integer d, solution is found,
otherwise solution is not found.
Step 5: Stop
Code:
#include<stdio.h>
#include<math.h>
void subset(int num, int n, int x[])
{
int i;
for(i = 1;i<=n;i++)
x[i]=0;
for(i=n;num!=0;i--)
{
x[i] = num%2;
num = num/2;
}
}
void main()
{
int a[50],x[50],n,j,i,d,sum,present = 0;
printf("Find subset of the given set whose sum is equal to a given integer \n");
printf("\n Enter the number of elements of the set\n");
scanf("%d",&n);
if(n>0 && n<90)
{
printf("\n Enter the elements of the set \n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
}
else
{
printf("Enter the valid number of elements\n");
}
printf("\n Enter the positive integer sum\n");
scanf("%d",&d);
if(d>0)
{
for(i=1;i<=pow(2,n)-1; i++)
{
subset(i,n,x);
sum=0;
for(j=1;j<=n;j++)
if(x[j]==1)
sum = sum +a[j];
if(d==sum)
{
printf("\n subset={");
present = 1;
for(j=1;j<=n;j++)
if(x[j]==1)
printf("%d ",a[j]);
printf("}=%d",d);
}
}
}
else
{
printf("Enter the valid positive integer\n");
}
if(present==0)
printf("solution does not exist");
}
11) Design and implement C/C++ Program for N Queen's problem using
Backtracking.
Aim:
To Implement N Queen's problem using Back Tracking
Problem Statement:
The problem is to place n queens on an n by n matrix so that no two queens attack
each other by being in same row or in the same column or on the same diagonal.
Algorithm:
ALGORITHM NQueen(K,n)
// Using backtracking
// possible placements of ‘n’ queen on n*n chessboard
For i:= 1 to n do
If Place(k,i) then
x[k]=I;
if k=n then write x[1:n]
else NQueen(k+1,n)
end if
end for
ALGORITHM Place(k,i)
// return true if a queen can be placed in kth row and ith column
// otherwise return false
Code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int b[20], count;
int place(int row, int col)
{
int i;
for(i = 1; i < row; i++)
{
if(b[i] == col || abs(b[i] - col) == abs(row - i))
return 0;
}
return 1;
}
void dis(int n)
{
int i, j;
printf("\n Solution number: %d\n", ++count);
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
if(b[i] == j)
printf("\tQ");
else
printf("\t*");
}
printf("\n");
}
printf("\n\n");
}
void queen(int row, int n)
{
int col;
for(col = 1; col <= n; col++)
{
if(place(row, col))
{
b[row] = col;
if(row == n)
dis(n);
else
queen(row + 1, n);
}
}
}
Aim
This program first calculates the profit-to-weight ratio for each item, then sorts the
items based on this ratio in non-increasing order. It then fills the knapsack greedily by
selecting items with the highest ratio until the knapsack is full. If there's space left in the
knapsack after selecting whole items, it adds fractional parts of the next item. Finally, it prints
the optimal solution and the solution vector.
Code
#include <stdio.h>
#define MAX 50
temp2 = p[i];
p[i] = p[j];
p[j] = temp2;
}
}
}
int currentWeight = 0;
maxprofit = 0.0;
int main() {
printf("Enter the number of objects: ");
scanf("%d", &n);
greedyKnapsack(n, w, p, m);
return 0;
}
VIVA questions
1. What is Algorithm?
2. Name the design techniques.
3. Which is efficient Sorting technique?
4. Which sorting technique has the lowest worst case efficiency?
5. Which sorting technique is space efficient?
6. Which sorting technique is Time efficient?
7. Define order of growth.
8. How binary search is advantageous over linear search?
9. What is CLK_TCK?
10. What is divide &conquer technique?
11. Give few problems which can be solved using divide &conquer technique.
12. What is dynamic programming?
13. Give few problems which can be solved using dynamic programming.
14. What is Back Tracking?
15. Define N-Queens problem.
16. What is Brute force Methodology?
17. What is Greedy Technique?
18. Give few problems which can be solved using Greedy Technique.
19. Which is the efficient method for finding MST?
20. What is MST?
21. What is DFS& BFS?
22. What is a heap?
23. What is Clock ( ) function?
24. Which is the header to include Clock function?
25. What are P NP problems?
26. Which are the String Matching algorithms?
27. What is Transitive closure?
28. Define Knapsack problem.
29. Define topological sorting?
30. Which algorithm used for checking graph is connected or not?