Algorithms Lab Manual for CSE-AI
Algorithms Lab Manual for CSE-AI
PREPARED BY:
PRATHIBHA A
Assistant Professor
Department of CSE-AI
SVCE,Bangalore
1
VISION :
Promoting prosperity of mankind by augmenting human resource capital through Quality Technical Education
and training in Artificial Intelligence Department.
MISSION:
The mission of Artificial Intelligence is to accomplish excellence in the field of Artificial Intelligence technical
education through education, research and service needs of society. And also to educate students in the area of
artificial intelligence by providing best practices of teaching learning process for careers in software are industry
or higher education.
M1: For acquiring the new skills and technology of artificial technology in software field and research field.
M2: To be a model center for education and training in the frontier areas of education by quality technical
education and training.
M3: To get excellence in the technical education through education, research and service needed by the society.
PROGRAMME OUTCOMES
Environment and Sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts and demonstrate the knowledge of and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the relevant scientific and/or engineering practices.
2
Individual and team work: Function effectively as an individual and as a member or leader indiverse
teams and in multi disciplinary settings.
Communication: Communicate effectively on complex engineering activities with the engineering
community and with the society-at-large, such as being able to comprehend and write effective reports
and design documentation, make effective presentations and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work as a member and leader in a team tomanage
projects and in multidisciplinary environments.
Life-long learning: Recognize the need for and above have the preparation and ability to engage in
independent and life-long learning in the broadcast context of technological changes.
PEO1 Graduates will have solid basics in Mathematics, Programming, Machine Learning, Artificial Intelligence
and Data Science fundamentals and advancements to solve technical problems.
PEO2 Graduates will have the capability to apply their knowledge and skills acquired to solve the issues in real
world Artificial Intelligence and Data Science sectors and to develop feasible and viable systems.
PEO3 Graduates will have the potential to participate in life-long learning through the successful completion of
advanced degrees, continuing education, certifications and/or other professional developments.
PEO4 Graduates will have the ability to apply the gained knowledge to improve the society ensuring ethical
and moral values.
Course Objectives:
This laboratory course enables students to get practical experience in design, develop,
implement, analyze and evaluation/testing of
● To Measure and compare the performance of different algorithms to determine their efficiency
and suitability for specific tasks.
4
SYLLABUS
[Link]. DETAILS HOURS
5
Design and implement C/C++ Program to sort a given set of n integer
11 elements using Merge Sort method and compute its time complexity. 2
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. 2
TOTAL HOURS 24
6
PROGRAM 1:
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given
connected undirected graph using Kruskal's algorithm.
Aim : To apply Kruskal's Algorithm for computing the minimum spanning tree is directly based on the generic
MST algorithm. It builds the MST in forest.
Definition: Kruskal’s algorithm is an algorithm in graph theory that finds a minimum spanning tree for a connected weighted
graph. This mean it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the
edges in the tree is minimized. If the graph is not connected, then it finds a minimum spanning forest. It is an example of a
greedy algorithm.
Efficiency: With an efficient sorting algorithm, the time efficiency of Kruskal’s algorithm will be in O(│E│log│E│)
Algorithm
Start with an empty set A, and select at every stage the shortest edge that has not been chosen or rejected, regardless
of where this edge is situated in graph.
If an edge (u, v) connects two different trees, then (u, v) is added to the set of edges of the MST, and two
trees connected by an edge (u, v) are merged into a single tree.
On the other hand, if an edge (u, v) connects two vertices in the same tree, then edge (u, v) is discarded.
Kruskals algorithm can be implemented using disjoint set data structure or priority queue data structure.
MST_KRUSKAL (G, w)
7
PROGRAM
OUTPUT
Design and implement C/C++ Program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Prim's algorithm.
Aim:To find minimum spanning tree of a given graph using prim’s algorithm
Definition: Prim’s is an algorithm that finds a minimum spanning tree for a connected weighted undirected graph. This means
it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all edges in the tree is
minimized. Prim’s algorithm is an example of a greedy algorithm.
Algorithm
MST_PRIM (G, w, v)
1. Q ← V[G]
2. for each u in Q do
3. key [u] ← ∞
4. key [r] ← 0
5. π[r] ← NIl
6. while queue is not empty do
7. u ← EXTRACT_MIN (Q)
8. for each v in Adj[u] do
9. if v is in Q and w(u, v) < key [v]
10. then π[v] ← w(u, v)
11. key [v] ← w(u, v)
PROGRAM:
#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++)
10
{
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("\nEnter n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\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=%d",res);
getch();}
11
OUTPUT:
Enter n value:4
4 -> 1 sum=0
4 -> 2 sum=2
1 -> 3 sum=4
Cost=4
12
PROGRAM 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.
Definition: The Floyd algorithm is a graph analysis algorithm for finding shortest paths in a weighted graph (with positive or
negative edge weights). A single execution of the algorithm will find the lengths (summed weights) of the shortest paths
between all pairs of vertices though it does not return details of the paths themselves. The algorithm is an example of dynamic
programming.
Algorithm:
Floyd’s Algorithm
Accept no .of vertices
Call graph function to read weighted graph // w(i,j)
Set D[ ] <- weighted graph matrix // get D {d(i,j)} for k=0
// If there is a cycle in graph, abort. How to find?
Repeat for k = 1 to n
Repeat for i = 1 to n
Repeat for j = 1 to n
D[i,j] = min {D[i,j], D[i,k] + D[k,j]}
Print D
PROGRAM
#include<stdio.h>
#include<conio.h>
#define INF 999
int min(int a,int b)
{
return(a<b)?a:b;}
13
void floyd(int p[][10],int n)
{
int i,j,k;
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]);
}
void main()
{
int a[10][10],n,i,j;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d",&a[i][j]);
floyd(a,n);
printf("\nShortest path matrix\n");
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
printf("%d ",a[i][j]);
printf("\n");
}
getch();
}
OUTPUT:
Enter the n value:4
Enter the graph data:
0 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0
Shortest path matrix
0 10 3 4
2056
7701
6 16 9 0
14
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
PROGRAM 3 B:
Definition:The Floyd-Warshall algorithm is a graph analysis algorithm for finding shortest paths in a weighted graph. A
single execution of the algorithm will find the lengths of the shortest path between all pairs of vertices though it does not
return details of the paths themselves. The algorithm is an example of Dynamic programming.
Algorithm
//Input: Adjacency matrix of digraph
//Output: R, transitive closure of digraph
Accept no .of vertices
Call graph function to read directed graph
Set R[ ] <- digraph matrix // get R {r(i,j)} for k=0
Print digraph
Repeat for k = 1 to n
Repeat for i = 1 to n
Repeat for j = 1 to n
R(i,j) = 1 if
{rij(k-1) = 1 OR
rik(k-1) = 1 and rkj(k-1) = 1}
Print R
PROGRAM:
#include<stdio.h>
void warsh(int p[][10],int n)
{
int i,j,k;
for(k=1; k<=n; k++)
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
p[i][j]=p[i][j] || p[i][k] && p[k][j];
}
int main()
{
int a[10][10],n,i,j;
printf("\nEnter the n value:");
15
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
scanf("%d",&n);
printf("\nEnter the graph data:\n");
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
scanf("%d",&a[i][j]);
warsh(a,n);
printf("\nResultant path matrix\n");
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
printf("%d ",a[i][j]);
printf("\n");
}
return 0;
}
OUTPUT
16
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
PROGRAM 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.
Definition: Dijikstra’s algorithm -For a given source vertex(node) in the graph, the algorithm finds the path with lowest cost
between that vertex and every other vertex. It can also be used for finding cost of shortest paths from a single vertex to a
single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined.
2
Efficiency:1) )-graph represented by weighted matrix and priority queue as unordered array
2)O(│E│log│v│)-graph represented by adjacency lists and priority queue as min-heap
Algorithm: Dijikstra(G,s)
//Dijikstra’s algorithm for single source shortest path
//input:A weighted connected graph with non negative weights and its vertex s
//output:The length dv of a shortest path from s to v and penultimate vertex p v for every vertex v in V
Initialize(Q)
for every vertex v in V do
dv<-∞;Pv<-null
Insert(Q,v,dv)
Ds<-0; Decrease(Q,s,ds);VT<-ǿ
for i<- 0 to │V│-1 do
u*<-DeleteMin(Q)
VT<-VT U{u*}
For every vertex u in V-VT that is adjacent to u* do
If du*+w(u*,u)<du
du<- du*+w(u*,u); pu<-u*
Decrease(Q,u,du)
17
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
PROGRAM :
#include<stdio.h>
int v[10],min,u,i,j;
d[i]=c[s][i];
v[i]=0;
v[s]=1;
min=INF;
min=d[j];
u=j;
18
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
v[u]=1;
d[j]=d[u]+c[u][j];
int main()
int c[10][10],d[10],i,j,s,sum,n;
printf("\nEnter n value:");
scanf("%d",&n);
scanf("%d",&c[i][j]);
scanf("%d",&s);
dijkstra(c,n,s,d);
return 0;}
19
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
OUTPUT:
Enter n value:4
20
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
PROGRAM 5:
Design and implement C/C++ Program to obtain the Topological ordering of vertices in a
given digraph.
#include<stdio.h>
#include<conio.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 n value:");
scanf("%d",&n);
for(i=1; i<=n; i++)
21
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
id[i]=0;
printf("\nEnter the graph data:\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]);
}
getch();
}
OUTPUT:
PROGRAM 6:
Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic
Programming method.
ALGORITHM
PROGRAM
#include<stdio.h>
int w[10],p[10],n;
int max(int a,int b)
{
return a>b?a:b;
}
int knap(int i,int m)
{
23
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
if(i==n) return w[i]>m?0:p[i];
if(w[i]>m) return knap(i+1,m);
return max(knap(i+1,m),knap(i+1,m-w[i])+p[i]);
}
int main()
{
int m,i,max_profit;
printf("\nEnter the no. of objects:");
scanf("%d",&n);
printf("\nEnter the knapsack capacity:");
scanf("%d",&m);
printf("\nEnter profit followed by weight:\n");
for(i=1; i<=n; i++)
scanf("%d %d",&p[i],&w[i]);
max_profit=knap(1,m);
printf("\nMax profit=%d",max_profit);
return 0;
}
OUTPUT:
Max profit=100
24
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
PROGRAM 7:
Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack
problems using greedy approximation method.
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.
Here's a simplified version of the C program to solve discrete Knapsack and continuous Knapsack problems using the greedy
approximation method:
#include <stdio.h>
#define MAX 50
int p[MAX], w[MAX], x[MAX];
double maxprofit;
int n, m, i;
void greedyKnapsack(int n, int w[], int p[], int m)
{
double ratio[MAX];
temp2 = p[i];
p[i] = p[j];
25
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
p[j] = temp2;
}
}
}
int currentWeight = 0;
maxprofit = 0.0;
// Fill the knapsack with items
for (i = 0; i < n; i++)
{
if (currentWeight + w[i] <= m)
{
x[i] = 1; // Item i is selected
currentWeight += w[i];
maxprofit += p[i];
}
else
{
// Fractional part of item i is selected
x[i] = (m - currentWeight) / (double)w[i];
maxprofit += x[i] * p[i];
break;
}
}
printf("Optimal solution for greedy method: %.1f\n", maxprofit);
printf("Solution vector for greedy method: ");
for (i = 0; i < n; i++)
printf("%d\t", x[i]);
}
int main()
{
printf("Enter the number of objects: ");
scanf("%d", &n);
printf("Enter the objects' weights: ");
for (i = 0; i < n; i++)
scanf("%d", &w[i]);
printf("Enter the objects' profits: ");
for (i = 0; i < n; i++)
scanf("%d", &p[i]);
printf("Enter the maximum capacity: ");
scanf("%d", &m);
greedyKnapsack(n, w, p, m);
return 0;
26
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
}
OUTPUT:
27
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
PROGRAM 8:
Design and implement C/C++ Program to 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.
AIM: An instance of the Subset Sum problem is a pair (S, t), where S = {x1, x2, ..., xn} is a set of positive integers and t(the
target) is a positive integer. The decision problem asks for a subset of S whose sum is as large as possible, but not larger than
t.
Algorithm: SumOfSub (s, k, r)
//Values of x[ j ], 1 <= j < k, have been determined
//Node creation at level k taking place: also call for creation at level K+1 if possible
// s = sum of 1 to k-1 elements and r is sum of k to n elements
//generating left child that means including k in solution
Set x[k] = 1
If (s + s[k] = d) then subset found, print solution
If (s + s[k] + s[k+1] <=d)
then SumOfSum (s + s[k], k+1, r – s[k])
//Generate right child i.e. element k absent
If (s + r - s[k] >=d) AND (s + s[k+1] )<=d
THEN { x[k]=0;
SumOfSub(s, k+1, r – s[k])
PROGRAM
#include<stdio.h>
#define MAX 10
int s[MAX],x[MAX],d;
void sumofsub(int p,int k,int r)
{
int i;
x[k]=1;
if((p+s[k])==d)
{
for(i=1; i<=k; i++)
if(x[i]==1)
printf("%d ",s[i]);
printf("\n");
}
else if(p+s[k]+s[k+1]<=d)
sumofsub(p+s[k],k+1,r
-s[k]);
if((p+r
28
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
-s[k]>=d) && (p+s[k+1]<=d))
{
x[k]=0;
sumofsub(p,k+1,r
-s[k]);
}
}
int main()
{
int i,n,sum=0;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the set in increasing order:");
for(i=1; i<=n; i++)
scanf("%d",&s[i]);
printf("\nEnter the max subset value:");
scanf("%d",&d);
for(i=1; i<=n; i++)
sum=sum+s[i];
if(sum<d || s[1]>d)
printf("\nNo subset possible");
else
sumofsub(0,1,sum);
return 0;
}
OUTPUT:
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.
Aim: 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.
Definition: selection sort is a sorting routine that scans a list of items repeatedly and, on each pass, selects the item with the
lowest value and places it in its final position. It is based on brute force approach. Sequential search is a Θ(n 2) algorithm on
all inputs.
Algorithm:
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]
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int n;
printf("Enter number of elements: ");
scanf("%d", &n); // Read the number of elements from the user
if (n <= 5000)
{
printf("Please enter a value greater than 5000\n");
return 1; // Exit if the number of elements is not greater than 5000
}
OUTPUT:
Enter number of elements: 6000
Time taken to sort 6000 elements: 0.031000 seconds
********************************************************************
********************************************************************
********************************************************************
********************************************************************
PROGRAM 10
32
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
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.
Aim:
The aim of this program is to sort ‘n’ randomly generated elements using Quick sort and Plotting the graph of the time
taken to sort n elements versus n.
Definition: Quick sort is based on the Divide and conquer approach. Quick sort divides array according to their value.
Partition is the situation where all the elements before some position s are smaller than or equal to A[s] and all the elements
after position s are greater than or equal to A[s].
Efficiency: Cbest(n) Є Θ(nlog2n),Cworst(n) ЄΘ(n2),Cavg(n)Є1.38nlog2n
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
33
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
// Function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
34
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
// Function to generate random numbers
void generateRandomNumbers(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
arr[i] = rand() % 100000; // Generate random numbers between 0 and 99999
}
}
int main()
{
int n;
printf("Enter number of elements: ");
scanf("%d", &n); // Read the number of elements from the user
if (n <= 5000)
{
printf("Please enter a value greater than 5000\n");
return 1; // Exit if the number of elements is not greater than 5000
}
OUTPUT:
********************************************************************
********************************************************************
Enter number of elements: 30000
Time taken to sort 30000 elements: 0.011000 seconds
********************************************************************
********************************************************************
36
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
PROGRAM 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.
Aim:
The aim of this program is to sort ‘n’ randomly generated elements using Merge sort and Plotting the graph of the time
taken to sort n elements versus n.
Definition: Merge sort is a sort algorithm based on divide and conquer technique. It divides the array element based on the
position in the array. The concept is that we first break the list into two smaller lists of roughly the same size, and then use
merge sort recursively on the subproblems, until they cannot subdivide anymore. Then, we can merge by stepping through the
lists in linear time. Its time efficiency is Θ(n log n).
Algorithm: Merge sort (A[0…n-1]
// Sorts array A[0..n-1] by Recursive merge sort
// Input : An array A[0..n-1] elements
// Output : Array A[0..n-1] sorted in non decreasing 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)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
i = 0;
j = 0;
k = left;
free(L);
free(R);
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
39
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
if (n <= 5000)
{
printf("Please enter a value greater than 5000\n");
return 1; // Exit if the number of elements is not greater than 5000
}
generateRandomArray(arr, n);
// Repeat the sorting process multiple times to increase duration for timing
clock_t start = clock();
for (int i = 0; i < 1000; i++)
{
mergeSort(arr, 0, n - 1);
}
clock_t end = clock();
free(arr);
return 0;
}
OUTPUT:
********************************************************************
40
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
Enter number of elements: 7000
Time taken to sort 7000 elements: 0.000752 seconds
********************************************************************
********************************************************************
********************************************************************
********************************************************************
********************************************************************
********************************************************************
********************************************************************
Enter number of elements: 15000
Time taken to sort 15000 elements: 0.003563 seconds
41
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
PROGRAM 12
Design and implement C/C++ Program for N Queen’s problem using Backtracking.
Algorithm:
/* outputs all possible acceptable positions of n queens on n x n chessboard */
// Initialize x [ ] to zero
// Set k = 1 start with first queen
Repeat for i = 1 to n // try all columns one by one for kth queen
if Place (k, i) true then
{
x(k) = i // place kth queen in column i
if (k=n) all queens placed and hence print output (x[ ])
else NQueens(K+1,n) //try for next queen
}
Place (k,i)
/* finds if kth queen in kth row can be placed in column i or not; returns true if queen can be placed */
// x[1,2, . . . k-1] have been defined
//queens at (p, q) & (r, s) attack if |p-r| = |q-s|
Repeat for j = 1 to (k-1)
if any earlier jth queen is in ith column ( x[j]= i)
or in same diagonal ( abs(x[ j] - i) = abs( j - k) )
then kth queen cannot be placed (return false)
return true (as all positions checked and no objection)
PROGRAM
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
return true;
}
// Consider this column and try placing this queen in all rows one by one
for (int i = 0; i < N; i++)
{
if (isSafe(board, N, i, col))
{
// Place this queen in board[i][col]
board[i][col] = 1;
// If the queen cannot be placed in any row in this column col, then return false
return false;
}
bool solveNQ(int N)
{
int **board = (int **)malloc(N * sizeof(int *));
for (int i = 0; i < N; i++)
{
board[i] = (int *)malloc(N * sizeof(int));
for (int j = 0; j < N; j++)
44
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
{
board[i][j] = 0;
}
}
if (!solveNQUtil(board, N, 0))
{
printf("Solution does not exist\n");
for (int i = 0; i < N; i++)
{
free(board[i]);
}
free(board);
return false;
}
printSolution(board, N);
int main()
{
int N;
printf("Enter the number of queens: ");
scanf("%d", &N);
solveNQ(N);
return 0;
}
OUTPUT:
45
DESIGN AND ANALYSIS OF ALGORITHMS LABORATORY(BCSL404)
************************OUTPUT-1************************
************************OUTPUT-2************************
46