Analysis and Design of Algorithms - Lab Manual
Analysis and Design of Algorithms - Lab Manual
1
Dept(s). of AI&ML and CD
Syllabus
Analysis & Design of Algorithms Lab Semester 4
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.
[Link] 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.
2
Dept(s). of AI&ML and CD
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.
3
Dept(s). of AI&ML and CD
marks scored by the student.
Semester End Evaluation (SEE):
SEE marks for the practical course are 50 Marks.
#include <stdio.h>
#define MAX 30
edge_list elist;
int Graph[MAX][MAX], n;
edge_list spanlist;
void kruskalAlgo();
int find(int belongs[], int vertexno);
void applyUnion(int belongs[], int c1, int c2);
void sort();
void print();
4
Dept(s). of AI&ML and CD
[Link][elist.n].w = Graph[i][j];
elist.n++;
}
}
sort();
spanlist.n = 0;
if (cno1 != cno2) {
[Link][spanlist.n] = [Link][i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}
// Sorting algo
void sort() {
int i, j;
edge temp;
5
Dept(s). of AI&ML and CD
[Link][j + 1] = temp;
}
}
int main() {
int i, j, total_cost;
n = 6;
Graph[0][0] = 0;
Graph[0][1] = 4;
Graph[0][2] = 4;
Graph[0][3] = 0;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;
Graph[1][0] = 4;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 0;
Graph[1][6] = 0;
Graph[2][0] = 4;
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 3;
Graph[2][4] = 4;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 0;
6
Dept(s). of AI&ML and CD
Graph[3][1] = 0;
Graph[3][2] = 3;
Graph[3][3] = 0;
Graph[3][4] = 3;
Graph[3][5] = 0;
Graph[3][6] = 0;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 4;
Graph[4][3] = 3;
Graph[4][4] = 0;
Graph[4][5] = 0;
Graph[4][6] = 0;
Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 2;
Graph[5][3] = 0;
Graph[5][4] = 3;
Graph[5][5] = 0;
Graph[5][6] = 0;
kruskalAlgo();
print();
}
OUTPUT
2-1:2
5-2:2
3-2:3
4-3:3
1-0:4
Spanning tree cost: 14
Explanation
[Link] File and Macro Definitions:
#include <stdio.h>
#define MAX 30
7
Dept(s). of AI&ML and CD
- The code includes the standard input-output library ( stdio.h ) for input/output operations.
- A macro MAX is defined to represent the maximum number of vertices or edges in the graph.
void kruskalAlgo();
int find(int belongs[], int vertexno);
void applyUnion(int belongs[], int c1, int c2);
void sort();
void print();
8
Dept(s). of AI&ML and CD
[Link][elist.n].w = Graph[i][j];
elist.n++;
}
}
spanlist.n = 0;
if (cno1 != cno2) {
[Link][spanlist.n] = [Link][i];
spanlist.n++;
applyUnion(belongs, cno1, cno2);
}
}
}
- The kruskalAlgo() function implements Kruskal's algorithm to find the Minimum Spanning Tree
(MST) of the graph.
- It constructs a list of all edges in the graph, sorts them based on their weights, and then applies
Kruskal's algorithm to select the edges for the MST.
- The belongs[] array keeps track of which set each vertex belongs to.
- The applyUnion() function is called to merge two sets when adding an edge to the MST.
9
Dept(s). of AI&ML and CD
6. Sorting Function sort() :
void sort() {
int i, j;
edge temp;
8. Main Function:
int main() {
// Graph initialization
n = 6;
// Graph adjacency matrix initialization
// (omitted for brevity)
kruskalAlgo(); // Apply Kruskal's algorithm
print(); // Print the MST
}
- The main() function initializes the graph and calls the kruskalAlgo() function to find the MST
using Kruskal's algorithm.
- Finally, it calls the print() function to print the MST and its total cost.
10
Dept(s). of AI&ML and CD
This code implements Kruskal's algorithm to find the Minimum Spanning Tree (MST) of a given graph.
It constructs a list of edges, sorts them by weight, and then selects edges one by one while avoiding
cycles to form the MST.
2. Design and implement C/C++ Program to find Minimum Cost
Spanning Tree of a given connected undirected graph using Prim's
algorithm
// Prim's Algorithm in C
#include<stdio.h>
#include<stdbool.h>
int main() {
int no_edge; // number of edge
return 0;
}
OUTPUT
Edge : Weight
0-1:9
12
Dept(s). of AI&ML and CD
1 - 3 : 19
3 - 4 : 31
3 - 2 : 51
Explanation
1. Header Files and Macros:
c
#include<stdio.h>
#include<stdbool.h>
- The code includes standard input-output library ( stdio.h ) for input/output operations and a
header for handling boolean values ( stdbool.h ).
- INF is defined as a very large value to represent infinity, used for initialization purposes.
- V is defined as 5, representing the number of vertices in the graph.
2. Graph Representation:
int G[V][V] = {
{0, 9, 75, 0, 0},
{9, 0, 95, 19, 42},
{75, 95, 0, 51, 66},
{0, 19, 51, 0, 31},
{0, 42, 66, 31, 0}
};
- The graph is represented as a 2D array G[][] , where G[i][j] represents the weight of the edge
between vertices i and j .
- Here, G represents a weighted undirected graph with 5 vertices.
3. Main Function:
int main() {
int no_edge;
int selected[V];
memset(selected, false, sizeof(selected));
no_edge = 0;
selected[0] = true;
int x, y;
printf("Edge : Weight\n");
13
Dept(s). of AI&ML and CD
- main() function starts execution.
- no_edge is initialized to keep track of the number of edges in the MST.
- selected[] array is initialized to keep track of vertices that are already included in the MST.
- Memory is set to false for all elements of selected[] array using memset() .
- no_edge is set to 0, indicating no edges are selected initially.
- The 0th vertex is marked as selected since the MST starts with this vertex.
- Variables x and y are declared to track the edge being added to the MST.
- The message "Edge : Weight" is printed to indicate the start of printing MST edges.
4. Prim's Algorithm Execution:
return 0;
}
- The main() function ends, and the program returns 0 to the operating system, indicating
successful execution.
14
Dept(s). of AI&ML and CD
This program effectively implements Prim's algorithm to find the Minimum Spanning Tree (MST) of a
given graph. It traverses the graph and selects the minimum weight edges until the MST is formed.
15
Dept(s). of AI&ML and CD
}
int main() {
int graph[V][V] = {
{0, INF, 3, INF},
{2, 0, INF, INF},
{INF, 7, 0, 1},
{6, INF, INF, 0}
};
floydWarshall(graph);
return 0;
}
OUTPUT
The following matrix shows the shortest distances between every pair of vertices:
0 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0
EXPLANATION
1. Header and Definitions:
- The program includes standard input-output library ( stdio.h ).
- It defines INF (infinity) to represent infinite distance and V as the number of vertices in the
graph.
2. Function Prototypes:
- printSolution() : Prints the solution matrix.
- floydWarshall() : Implementation of Floyd Warshall algorithm to find the shortest paths between
all pairs of vertices.
3. Function Definitions:
- printSolution() : Iterates through the solution matrix and prints the shortest distances between all
pairs of vertices. It prints "INF" for unreachable pairs.
- floydWarshall() : Implements Floyd Warshall algorithm. It initializes the distance matrix with the
given graph. Then, it updates the distance matrix by considering all intermediate vertices. Finally, it
calls printSolution() to print the solution matrix.
4. Main Function:
16
Dept(s). of AI&ML and CD
- Initializes the input graph with the provided distances between vertices.
- Calls floydWarshall() with the input graph to find the shortest paths between all pairs of vertices.
This program efficiently computes the shortest paths between all pairs of vertices in a given graph
using Floyd's algorithm.
int main() {
int graph[V][V] = {
{1, 1, 0, 1},
{0, 1, 1, 0},
{0, 0, 1, 1},
{0, 0, 0, 1}
};
return 0;
}
OUTPUT
/tmp/goOugZR4N3.o
Transitive Closure Matrix:
1111
0111
0011
0001
EXPLANATION
Header and Definitions:
The program includes standard input-output library (stdio.h).
It defines V as the number of vertices in the graph.
Function Prototypes:
printTransitiveClosure(): Prints the transitive closure matrix.
transitiveClosure(): Implementation of Warshall's algorithm to find the transitive closure.
Function Definitions:
printTransitiveClosure(): Iterates through the transitive closure matrix and prints its elements.
transitiveClosure(): Implements Warshall's algorithm. It initializes the closure matrix with the given
graph. Then, it updates the closure matrix by considering all intermediate vertices. Finally, it calls
printTransitiveClosure() to print the transitive closure matrix.
Main Function:
Initializes the input graph with the given adjacency matrix representing the directed graph.
Calls transitiveClosure() with the input graph to find the transitive closure.
18
Dept(s). of AI&ML and CD
This program efficiently computes the transitive closure of a directed graph using Warshall's
algorithm
#include <stdio.h>
#include <stdbool.h>
// Function to find the vertex with the minimum distance value, from the set of vertices
// not yet included in the shortest path tree
int minDistance(int dist[], bool sptSet[]) {
int min = INF, min_index;
return min_index;
}
int main() {
// Given graph in adjacency matrix representation
int graph[V][V] = {
{0, 4, 0, 0, 0, 0},
{4, 0, 8, 0, 0, 0},
{0, 8, 0, 7, 0, 4},
{0, 0, 7, 0, 9, 14},
{0, 0, 0, 9, 0, 10},
{0, 0, 4, 14, 10, 0}
};
return 0;
}
OUTPUT
EXPLANATION
1. Header Files and Definitions:
- The program includes standard input-output library ( stdio.h ) and a header for handling boolean
values ( stdbool.h ).
- V is defined as the number of vertices in the graph.
- INF is defined as a very large value to represent infinite distance.
2. Function Prototypes:
- minDistance() : Finds the vertex with the minimum distance value from the set of vertices not yet
included in the shortest path tree.
- printSolution() : Prints the shortest distances from the source vertex to all other vertices.
- dijkstra() : Implements Dijkstra's algorithm to find the shortest paths from the source vertex to all
other vertices.
3. Function Definitions:
- minDistance() : Finds the vertex with the minimum distance value among the vertices not yet
included in the shortest path tree ( sptSet[] ).
- printSolution() : Prints the shortest distances from the source vertex to all other vertices.
- dijkstra() : Implements Dijkstra's algorithm. It initializes dist[] with INF and sptSet[] with false .
It then iteratively finds the shortest path for all vertices by selecting the vertex with the minimum
distance, marking it as processed, and updating the distances of its adjacent vertices if a shorter path
is found.
4. Main Function:
- Initializes the given graph in adjacency matrix representation.
21
Dept(s). of AI&ML and CD
- Calls dijkstra() with the graph and the source vertex to find the shortest paths from the source
vertex to all other vertices.
This program efficiently computes the shortest paths from a given vertex to all other vertices
in a weighted connected graph using Dijkstra's algorithm.
5. Design and implement C/C++ Program to obtain the Topological
ordering of vertices in a given digraph.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Initialize stack
void initialize(Stack *s) {
s->top = -1;
}
22
Dept(s). of AI&ML and CD
}
return graph;
}
push(s, vertex); // Push the vertex onto the stack after visiting all its adjacent vertices
}
23
Dept(s). of AI&ML and CD
for (int i = 0; i < graph->vertices; ++i) {
if (!visited[i])
DFS(graph, i, visited, &s);
}
int main() {
int vertices = 6; // Number of vertices in the graph
return 0;
}
OUTPUT
Topological ordering of vertices: 5 4 2 3 1 0
EXPLANATION
24
Dept(s). of AI&ML and CD
2. Graph Data Structure:
- We define a graph data structure to represent the directed graph.
3. Functions:
- initialize() , isEmpty() , push() , and pop() : Functions to handle the stack operations.
- createGraph() : Function to create a graph with the specified number of vertices.
- addEdge() : Function to add a directed edge between two vertices.
- DFS() : Function to perform Depth First Search traversal recursively. It marks vertices as visited
and explores them recursively.
- topologicalSort() : Function to perform topological sorting using Depth First Search. It iterates
through all vertices, performs DFS on unvisited vertices, and pushes the vertices onto the stack after
visiting all their adjacent vertices.
4. Main Function:
- We create a directed graph with a specified number of vertices.
- We add directed edges to the graph.
- We call topologicalSort() to obtain the topological ordering of vertices and print it.
This program efficiently computes the topological ordering of vertices in a given directed graph.
6. Design and implement C/C++ Program to solve 0/1 Knapsack problem using Dynamic Programming
method
#include <stdio.h>
25
Dept(s). of AI&ML and CD
}
}
int main() {
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50; // Knapsack capacity
int n = sizeof(val) / sizeof(val[0]); // Number of items
printf("Maximum value that can be obtained: %d\n", knapSack(W, wt, val, n));
return 0;
}
OUTPUT
EXPLANATION
Explanation of the program:
1. max() Function:
- The max() function returns the maximum of two integers.
2. knapSack() Function:
- The knapSack() function takes four arguments:
- W : The maximum capacity of the knapsack.
- wt[] : An array containing weights of items.
- val[] : An array containing values of items.
- n : The number of items.
- It uses dynamic programming to solve the 0/1 Knapsack problem. It builds a table K[][] where
K[i][w] represents the maximum value that can be obtained with a knapsack capacity of w and i
items.
- It iterates through all possible combinations of items and knapsack capacities and fills in the table
according to the optimal substructure of the problem.
- The final value at K[n][W] represents the maximum value that can be obtained with the given
constraints.
3. main() Function:
26
Dept(s). of AI&ML and CD
- In the main() function, we initialize values and weights of items and the capacity of the
knapsack.
- We call the knapSack() function with these parameters and print the maximum value that can be
obtained.
This program efficiently solves the 0/1 Knapsack problem using Dynamic Programming.
// Sort items based on their density in non-increasing order using insertion sort
27
Dept(s). of AI&ML and CD
for (int i = 1; i < n; i++) {
struct Item temp = items[i];
int j = i - 1;
while (j >= 0 && items[j].density < [Link]) {
items[j + 1] = items[j];
j--;
}
items[j + 1] = temp;
}
return totalValue;
}
// Sort items based on their density in non-increasing order using insertion sort
for (int i = 1; i < n; i++) {
struct Item temp = items[i];
int j = i - 1;
while (j >= 0 && items[j].density < [Link]) {
items[j + 1] = items[j];
j--;
}
items[j + 1] = temp;
}
28
Dept(s). of AI&ML and CD
totalValue += items[i].value;
capacity -= items[i].weight;
} else {
totalValue += (capacity * items[i].density);
capacity = 0;
}
}
return totalValue;
}
int main() {
// Sample data for discrete knapsack problem
struct Item discreteItems[] = {{10, 60}, {20, 100}, {30, 120}};
int n1 = sizeof(discreteItems) / sizeof(discreteItems[0]);
int discreteCapacity = 50;
// Compute and print solutions for discrete and continuous knapsack problems
printf("Discrete Knapsack Problem:\n");
int discreteResult = discreteKnapsack(discreteItems, n1, discreteCapacity);
printf("Maximum value obtained: %d\n\n", discreteResult);
return 0;
}
OUTPUT
EXPLANATION
29
Dept(s). of AI&ML and CD
1. Item Structure:
- Represents items with weight and value.
2. discreteKnapsack Function:
- Solves the discrete knapsack problem using the greedy approximation method.
- Calculates the density (value/weight ratio) for each item and sorts items based on their density in
non-increasing order.
- Iterates through sorted items and selects items greedily until the capacity is exhausted.
3. continuousKnapsack Function:
- Solves the continuous knapsack problem using the greedy approximation method.
- Calculates the density (value/weight ratio) for each item and sorts items based on their density in
non-increasing order.
- Iterates through sorted items and selects items greedily, allowing fractional parts of items to be
selected.
4. Main Function:
- Initializes sample data for both discrete and continuous knapsack problems.
- Computes and prints solutions for both problems.
// Function to find a subset of a given set whose sum is equal to a given positive integer
void findSubset(int set[], int n, int sum, int subset[], int subSize, int totalSum, int index) {
if (totalSum == sum) {
// Print the subset
printf("Subset found: { ");
for (int i = 0; i < subSize; i++)
printf("%d ", subset[i]);
printf("}\n");
return;
30
Dept(s). of AI&ML and CD
}
int main() {
int set[] = {12, 4, 5, 6, 7, 2, 3, 8, 9}; // Given set
int n = sizeof(set) / sizeof(set[0]); // Number of elements in the set
int sum = 15; // Given sum
int subset[MAX_SIZE]; // Array to store the subset
int subSize = 0; // Size of the subset
return 0;
}
OUTPUT
EXPLANATION
31
Dept(s). of AI&ML and CD
1. findSubset Function:
- This function recursively finds a subset of the given set whose sum is equal to the given positive
integer.
- It takes parameters:
- set[] : The given set of positive integers.
- n : The number of elements in the set.
- sum : The target sum to achieve.
- subset[] : An array to store the elements of the subset.
- subSize : The current size of the subset.
- totalSum : The current sum of the elements in the subset.
- index : The index of the current element being considered.
- It uses backtracking to explore all possible combinations of elements to form the subset.
- When the totalSum becomes equal to the given sum , it prints the subset.
2. Main Function:
- Initializes a sample set of positive integers and a target sum.
- Calls the findSubset function to find the subset(s) with the given sum.
This program will find and print the subset(s) of the given set whose sum is equal to the given
positive integer.
#include <stdio.h>
#include <stdlib.h>
32
Dept(s). of AI&ML and CD
#include <time.h>
int main() {
int n, i;
clock_t start, end;
double time_used;
start = clock();
selectionSort(arr, n);
end = clock();
33
Dept(s). of AI&ML and CD
}
free(arr);
return 0;
}
OUTPUT
(Second Part)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
34
Dept(s). of AI&ML and CD
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
// Swap arr[i] with the minimum element
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
int main() {
FILE *fp;
fp = fopen("sorting_times.csv", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
35
Dept(s). of AI&ML and CD
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC * 1000; // Time taken in
milliseconds
// Write to file
fprintf(fp, "%d,%.2f\n", n, cpu_time_used);
}
fclose(fp);
return 0;
}
OUTPUT
Plot a graph.
36
Dept(s). of AI&ML and CD
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.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
37
Dept(s). of AI&ML and CD
int main() {
int n, i;
clock_t start, end;
double time_used;
start = clock();
quickSort(arr, 0, n - 1);
end = clock();
free(arr);
return 0;
}
OUTPUT
38
Dept(s). of AI&ML and CD
13679
Time taken: 0.000000 seconds
(Second Part)
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
39
Dept(s). of AI&ML and CD
// Sort elements before partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
FILE *fp;
fp = fopen("sorting_times.csv", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
40
Dept(s). of AI&ML and CD
// Stop the timer
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC * 1000; // Time taken in
milliseconds
// Write to file
fprintf(fp, "%d,%.2f\n", n, cpu_time_used);
}
fclose(fp);
return 0;
}
OUTPUT
41
Dept(s). of AI&ML and CD
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.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
42
Dept(s). of AI&ML and CD
} else {
arr[k] = R[j];
j++;
}
k++;
}
int main() {
int n;
clock_t start, end;
double time_used;
43
Dept(s). of AI&ML and CD
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
start = clock();
mergeSort(arr, 0, n - 1);
end = clock();
free(arr);
return 0;
}
OUTPUT
44
Dept(s). of AI&ML and CD
(Second Part)
*
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
45
Dept(s). of AI&ML and CD
arr[k] = R[j];
j++;
k++;
}
}
int main() {
FILE *fp;
fp = fopen("sorting_times.csv", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
46
Dept(s). of AI&ML and CD
clock_t start, end;
double cpu_time_used;
// Write to file
fprintf(fp, "%d,%.2f\n", n, cpu_time_used);
}
fclose(fp);
return 0;
}
OUTPUT
47
Dept(s). of AI&ML and CD
Time taken to sort 4500 elements: 0.00 ms
Time taken to sort 5000 elements: 0.00 ms
Time taken to sort 5500 elements: 0.00 ms
Time taken to sort 6000 elements: 16.00 ms
Time taken to sort 6500 elements: 0.00 ms
Time taken to sort 7000 elements: 0.00 ms
Time taken to sort 7500 elements: 0.00 ms
Time taken to sort 8000 elements: 0.00 ms
Time taken to sort 8500 elements: 0.00 ms
Time taken to sort 9000 elements: 0.00 ms
Time taken to sort 9500 elements: 21.00 ms
Time taken to sort 10000 elements: 0.00 ms
Data saved to sorting_times.csv
Draw graph
48
Dept(s). of AI&ML and CD
for (i = 0; i < col; i++)
if (board[row][i])
return false;
return true;
}
// Consider this column and try placing this queen in all rows
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1; // Place the queen
return false; // If queen can't be placed in any row in this column, return false
}
// Main function to solve the N Queens problem and print the solution
void solveNQueensProblem() {
int board[N][N] = { {0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
49
Dept(s). of AI&ML and CD
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0} };
if (solveNQueens(board, 0) == false) {
printf("Solution does not exist");
return;
}
printSolution(board);
}
int main() {
solveNQueensProblem();
return 0;
}
OUTPUT
10000000
00000010
00001000
00000001
01000000
00010000
00000100
00100000
50
Dept(s). of AI&ML and CD