DAA_LabFile by RaviSir
DAA_LabFile by RaviSir
LABORATORY MANUAL
DESIGN & ANALYSIS OF ALGORITHMS
(BCS-553)
Name
Roll No.
Section-Batch
To provide globally competent professionals in the field of Computer Science & Engineering
embedded with sound technical knowledge, aptitude for research and innovation, and nurture
future leaders with ethical values to cater to the industrial & societal needs.
Mission of the Department
Mission 1: To provide quality education in both the theoretical and applied foundations of
Computer Science & Engineering.
Mission 2: Conduct research in Computer Science & Engineering resulting in innovations
thereby nurturing entrepreneurial thinking.
Mission 3: To inculcate team building skills and promote life-long learning with a high
societal and ethical values.
2
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
B. Tech Computer Science & Engineering Department has the following Program Educational
Objectives:
PEO1: Possess core theoretical and practical knowledge in Computer Science and Engineering for
successful career development in industry, pursuing higher studies or entrepreneurship.
PEO2: Ability to imbibe life long learning for global challenges to impact society and
environment.
PEO3: To demonstrate work productivity with leadership and managerial skills having ethics and
human value in progressive career path.
PEO4: To exhibit communication skill and collaborative skill plan and participate in
multidisciplinary fields of Computer Science & Engineering.
B.Tech Computer Science & Engineering Department has the following Program Specific
Outcomes:
PSO1: To analyze and demonstrate, the recent engineering practices, ethical values and strategies
in real time world problems to meet the challenges for the future.
PSO2: To develop adaptive computing system using computational intelligence strategies and
algorithmic design to address diverse challenges in data analysis and machine learning.
3
PROGRAM OUTCOMES
Engineering Graduates will be able to:
4
GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with
the synopsis / program / experiment details.
• Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
• Laboratory Record updated up to the last session experiments and other utensils (if
any) needed in the lab.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system / seat
is kept properly.
DETAILS OF THE EXPERIMENTS CONDUCTED
(TO BE USED BY THE STUDENTS IN THEIR RECORDS)
INDEX
DATE OF FACULTY
S.No TITLE OF THE EXPERIMENT
SUBMISSION SIGNATURE
10
STUDY AND EVALUATION SCHEME
Course Course
Teaching Scheme Credits Assigned
Code Name
Design &
BCS-503(T) Analysis of
Algorthms Theory Practical Tutorial Theory Practical Tutorial Total
BCS-553 (P)
03 02 01 03 01 01 05
(70 (50
Marks) Marks)
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science and Engineering
Course Name: Design & Analysis of Algorithms Lab Course Code: BCS-553
Semester / Year: 5th /3rd NBA Code: C 309
Bloom’s
COURSE OUTCOMES
Level
CO1(C309).1 Implement algorithm to solve problems by iterative approach. K2, K4
CO2(C309).2 Implement algorithm to solve problems by divide and conquer approach K3, K5
CO3(C309).3 Implement algorithm to solve problems by Greedy algorithm approach. K4, K5
Implement algorithm to solve problems by Dynamic programming,
CO4(C309).4 K4, K5
backtracking, branch and bound approach.
CO5(C309).5 Implement algorithm to solve problems by branch and bound approach. K3, K4
CO-PO Matrix
Course PO
PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
Outcome 1
C309.1 3 3 3 3 1 1 1 1 2 1 2 2 3 2
C309.2 3 3 3 3 1 1 1 1 2 1 2 2 3 2
C309.3 3 3 2 2 1 2 1 1 2 1 2 2 3 2
C309.4 3 3 3 3 2 2 1 1 2 1 2 2 3 2
C309.5 3 3 2 3 2 2 1 1 2 1 2 2 3 2
C309 3.0 3.0 2.60 2.80 1.40 1.60 1.00 1.00 2.00 1.00 2.00 2.00 3.00 2.00
LIST OF PROGRAMS
Theory Concept:
The Linear Search, or sequential search, is simply examining each element in a list one by one until the desired
element is found. The Linear Search is not very efficient. If the item of data to be found is at the end of the list, then
all previous items must be read and checked before the item that matches the search criteria is found.
Implementation:
#include <stdio.h>
#include <stdlib.h> // For exit function
void main() {
int i, temp, ser, a[100];
// Clear screen is not a standard function; remove it or replace with system("cls") for Windows
printf("Enter the number of elements to be entered: ");
scanf("%d", &temp);
// Ensure the number of elements does not exceed the array size
if (temp > 100) {
printf("Number of elements cannot exceed 100.\n");
return;
}
Theory Concept:
This type of searching an element in the given array, the array should have elements in sorted manner. Each
time the given element is compared with the middle element of given sorted array. And then it is decided to
divide the further the given array.
Implementation:
#include <stdio.h>
#include <stdlib.h>
void main() {
int i, temp, ser, a[100], beg = 0, mid, end;
// Ensure the number of elements does not exceed the array size
if (temp > 100) {
printf("Number of elements cannot exceed 100.\n");
return;
}
Output:
Experiment No. 2
Theory Concept:
Heap is a complete binary tree. When it is represented as an array for parent node located at nth position left child
and right child are located at 2n and 2n+1 th position. For maxheap larger element is found at parent node and largest
node at root node and vice versa for min heap. For the sorting problem first of all we create max heap by heafying the
given array. then interchange the position of root node and leaf node and remove the leaf node and keep it in an array
which is our resultant sorted array.
Implementation:
#include <stdio.h>
void display();
void create_heap();
void insert(int num, int loc);
void heap_sort();
void del_root(int last);
int main() {
int i;
printf("Enter number of elements: ");
scanf("%d", &n);
create_heap();
printf("Heap is:\n");
display();
heap_sort();
return 0;
}
Theory Concept:
It is based on divide and conquers method. It includes
1. Divide the main problem into sub problems.
2. Solve the main problem recursively.
3. Merging the solved sub problems into main solved problem.
Suppose we have an array A with n indices ranging from A0 to An − 1. We apply merge sort to A (A0. Ac − 1) and
A (Ac..An − 1) where c is the integer part of n / 2. When the two halves are returned, they will have been sorted. They
can now be merged together to form a sorted array. In most implementations it is stable, meaning that it preserves the
input order of equal elements in the sorted output.
Implementation:
#include <stdio.h>
#include <math.h>
// Function prototypes
void mergesort(int arr[], int p, int r);
void merge(int arr[], int p, int q, int r);
void main() {
int a[20], n, i;
// Merge function
void merge(int arr[], int p, int q, int r) {
int n1 = q - p + 1; // Size of the left subarray
int n2 = r - q; // Size of the right subarray
int L[n1 + 1], R[n2 + 1]; // Temporary arrays to hold the split data
int i, j, k;
Theory Concept:
In this sorting is we first find the smallest element and then exchanging it with the first element in array. Then finding
the second smallest element and then placing it on second position in the array and so on.
Implementation:
#include <stdio.h>
#define MAX 25
void main() {
int array[MAX], n, i, j, min_index, temp;
Theory Concept:
Let a0, ..., an-1 be the sequence to be sorted. At the beginning and after each iteration of the algorithm the sequence
consists of two parts: the first part a0, ..., ai-1 is already sorted, the second part ai, ..., an-1 is still unsorted (i 0, ...,
n).
In order to insert element ai into the sorted part, it is compared with ai-1, ai-2 etc. When an element aj with aj ai
is found, ai is inserted behind it. If no such element is found, then ai is inserted at the beginning of the sequence.
After inserting element ai the length of the sorted part has increased by one. In the next iteration, ai+1 is inserted
into the sorted part etc. While at the beginning the sorted part consists of element a0 only, at the end it consists of all
elements a0, ..., an-1.
Implementation:
#include <stdio.h>
#define MAX 25
void main() {
int array[MAX], n, i, j, key;
Output:
Experiment No. 6
Theory Concept:
It is based on divide and conquer paradigm for sorting array. It is the best practical choice for sorting because it is
remarkably efficient on average case: its expected running time is of order of nlogn. It works well in virtual memory.
Implementation:
#include <stdio.h>
// Function prototypes
void quicksort(int a[], int p, int r);
int partition(int a[], int p, int r);
void main() {
int a[10], i, m;
Output:
Experiment No. 7
Theory Concept:
There are n items in a store. For i =1,2, . . ., n, item i has weight wi > 0 and worth vi > 0. Thief can carry a maximum
weight of W pounds in a knapsack. In this version of a problem the items can be broken into smaller piece, so the
thief may decide to carry only a fraction xi of object i, where 0 = xi = 1. Item i contributes xiwi to the total weight in
the knapsack, and xivi to the value of the load. In Symbol, the fraction knapsack problem can be stated as follows.
maximize nSi=1 xivi subject to constraint nSi=1 xiwi
= W. It is clear that an optimal solution must fill the knapsack exactly, for otherwise we could add a fraction of one
of the remaining objects and increase the value of the load.
Implementation:
#include <stdio.h>
void simple_fill() {
int cur_w = W; // Current available capacity in the knapsack
float tot_v = 0.0; // Total value of items in the knapsack
int used[10] = {0}; // Keeps track of whether an object is used
int i, maxi;
int main() {
simple_fill();
return 0;
}
Output:
Experiment No. 8
Theory Concept:
Given a complete undirected graph G= (V, E) that has nonnegative integer cost c(u, v) associated with each edge (u,
v) in E, the problem is to find a hamiltonian cycle (tour) of G with minimum cost. A salesperson starts from the city
1 and has to visit six cities (1 through 6) and must come back to the starting city i.e., 1. The first route (left side) 1? 4
? 2 ? 5? 6 ? 3 ? 1 with the total length of 62 km, is a relevant selection but is not the best solution. The second route
(right side) 1 ? 2 ? 5? 4 ? 6 ? 3 ? 1 represents the much better solution as the total distance, 48 km, is less than for the
first route.
Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function Prototypes
void createProfit(int profitMatrix[N][N]);
void createRoute(int currentRoute[N]);
int evaluateRoute(int currentRoute[N], const int profitMatrix[N][N]);
void tryRoute(int currentRoute[N], int bestRoute[N], const int profitMatrix[N][N]);
void swap(int *item1, int *item2);
int main() {
// Declare necessary variables
int profitMatrix[N][N];
int currentRoute[N], bestRoute[N];
int value = 0;
long int start;
int kount = 0;
// Start timing
start = clock();
return 0;
}
tries++;
Theory Concept:
Consider a directed graph, G(N,A), where N and A are the set of nodes and arcs, respectively. Associated with each
arc (i,j) in A is a cost c(i,j). Let |N|=n and |A|=m. The problem is to find a rooted directed spanning tree, G(N,S) where
S is a subset of A such that the sum of c(i,j) for all (i,j) in S is minimized. The rooted directed spanning tree is defined
as a graph which connects, without any cycle, all nodes with n-1 arcs, i.e., each node, except the root, has one and
only one incoming arc.
Implementation:
#include<stdio.h>
#include<conio.h>
#define MAX 10
#define TEMP 0
#define PERM 1
#define FALSE 0
#define TRUE 1
#define infinity 9999
struct node
{
int predecessor;
int dist; /*Distance from predecessor */
int status;
};
struct edge
{
int u;
int v;
};
int adj[MAX][MAX];
int n;
main()
{
int i,j;
int path[MAX];
int wt_tree,count;
struct edge tree[MAX];
create_graph();
printf("Adjacency matrix is :\n");
display();
count = maketree(tree,&wt_tree);
create_graph()
{
int i,max_edges,origin,destin,wt;
for(i=1;i<=max_edges;i++)
{
printf("Enter edge %d(0 0 to quit) : ",i);
scanf("%d %d",&origin,&destin);
if((origin==0) && (destin==0))
break;
printf("Enter weight for this edge : ");
scanf("%d",&wt);
if( origin > n || destin > n || origin<=0 || destin<=0)
{
printf("Invalid edge!\n");
i--;
}
else
{
adj[origin][destin]=wt;
adj[destin][origin]=wt;
}
}/*End of for*/
if(i {
printf("Spanning tree is not possible\n");
exit(1);
}
}/*End of create_graph()*/
display()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%3d",adj[i][j]);
printf("\n");
}
}/*End of display()*/
int maketree(struct edge tree[MAX],int *weight)
{
struct node state[MAX];
int i,k,min,count,current,newdist;
int m;
int u1,v1;
*weight=0;
/*Make all nodes temporary*/
for(i=1;i<=n;i++)
{
state[i].predecessor=0;
state[i].dist = infinity;
state[i].status = TEMP;
}
/*Make first node permanent*/
state[1].predecessor=0;
state[1].dist = 0;
state[1].status = PERM;
state[current].status=PERM;
Output:
Experiment No. 10
Theory Concept:
In chess, a queen can move as far as she pleases, horizontally, vertically, or diagonally. A chess board has 8 rows and
8 columns. The standard 8 by 8 Queen's problem asks how to place 8 queens on an ordinary chess board so that none
of them can hit any other in one move.
Implementation:
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
class nQueens {
public:
nQueens(int n) {
this->n = n;
col = new int[n];
}
~nQueens() {
delete[] col;
}
void start();
void finish();
void queens(index i);
bool promising(index i);
void OutputSolution();
private:
int n;
int *col;
int numSolutions, numNonPromising, numPromising;
};
void nQueens::start() {
numSolutions = 0;
numNonPromising = 0;
numPromising = 0;
queens(0);
}
void nQueens::finish() {
std::cout << "# solutions = " << numSolutions;
std::cout << " # promising nodes = " << numPromising;
std::cout << " # non-promising nodes = " << numNonPromising << std::endl;
}
void nQueens::queens(index i) {
if (promising(i)) {
numPromising++;
if (i == n) {
numSolutions++;
OutputSolution();
} else {
for (index j = 0; j < n; j++) {
col[i] = j;
queens(i + 1);
}
}
} else {
numNonPromising++;
}
}
bool nQueens::promising(index i) {
for (index k = 0; k < i; k++) {
if (col[i] == col[k] || abs(col[i] - col[k]) == i - k) {
return false;
}
}
return true;
}
void nQueens::OutputSolution() {
std::cout << "Solution " << numSolutions << ": ";
for (index i = 0; i < n; i++) {
std::cout << "(" << i + 1 << "," << col[i] + 1 << ") ";
}
std::cout << std::endl;
}
return 0;
}
Output:
Experiment No. 11
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 non graph sheet. The elements can be read from a file
or can be generated using the random number generator. Demonstrate using Java how the
divide and- conquer method works along with its time complexity analysis: worst case,
average case and best case.
Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int n;
printf("Enter n value: ");
scanf("%d", &n);
printf("Quick Sort\n");
printf("1. Best/Average Case\n");
printf("2. Worst Case\n");
int choice;
scanf("%d", &choice);
// Perform QuickSort
quickSort(0, n - 1);
return 0;
}
// Partition function that rearranges elements and returns the pivot index
int partition(int low, int high) {
int pivot = arr[low]; // Pivot element
int i = low, j = high;
while (i < j) {
comparisons++;
// Move i to the right while arr[i] is less than or equal to pivot
while (i < high && arr[i] <= pivot) {
comparisons++;
i++;
}
// Move j to the left while arr[j] is greater than or equal to pivot
while (j > low && arr[j] >= pivot) {
comparisons++;
j--;
}
// If i < j, swap arr[i] and arr[j]
if (i < j) {
comparisons++;
interchange(i, j);
}
}
// Swap pivot into its correct position
interchange(low, j);
return j; // Return pivot index
}
Output:
Experiment No. 12
Sort a given set of n integer elements using Merge Sort method and compute its time
complexity. Run the program forvaried values of n> 5000, and record the time taken to sort.
Plot a graph of the time taken versus non graph sheet. The elements can be read from a file or
can be generated using the random number generator. Demonstrate how the divide and-
conquer method works along with its time complexity analysis: worst case, average case and
best case.
Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int n;
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int)); // Dynamically allocate memory for the array
if (a == NULL) {
printf("Memory allocation failed!\n");
return -1;
}
// Call mergeSort
mergeSort(a, 0, n - 1);
return 0;
}
// Merge function to combine two sorted subarrays into one sorted array
void merge(int a[], int low, int mid, int high) {
int i = low, j = mid + 1, k = low;
int *b = (int *)malloc((high - low + 1) * sizeof(int)); // Temporary array for merging
if (b == NULL) {
printf("Memory allocation failed!\n");
exit(-1);
}
Implement, the 0/1 Knapsack problem using (a) Dynamic Programming method (b) Greedy
method.
Theory Concept:
Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in
the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights
associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the
maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. You cannot
break an item, either pick the complete item or don’t pick it (0-1 property).
Given the weights and values of n items, we need to put these items in a knapsack of capacity W to get the maximum
total value in the knapsack.
In the 0-1 Knapsack problem, we are not allowed to break items. We either take the whole item or don’t take it.
Implementation:
#include <stdio.h>
#include <stdlib.h>
return totalValue;
}
int main() {
int weight[] = {10, 40, 20, 30};
int value[] = {60, 40, 100, 120};
int capacity = 50;
int n = sizeof(weight) / sizeof(weight[0]);
From a given vertex in a weighted connected graph, find shortest paths to other vertices
using Dijkstra's algorithm.
Thoery Concept:
Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given
graph. Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we
generate a SPT (shortest path tree) with a given source as a root. We maintain two sets, one set contains vertices
included in the shortest-path tree, other set includes vertices not yet included in the shortest-path tree. At every step
of the algorithm, we find a vertex that is in the other set (set of not yet included) and has minimum distance from the
source. Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex
to all other vertices in the given graph.
Implementation:
#include <stdio.h>
#include <limits.h>
#include <stdbool.h>
return min_index;
}
bool sptSet[V]; // sptSet[i] will be true if vertex i is included in shortest path tree
// Initialize all distances as INFINITE and sptSet[] as false
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = false;
}
return 0;
}
OUTPUT:
Experiment No. 15
Find Minimum Cost Spanning Tree of a given connected undirected graph using Kruskal's
algorithm. Use Union-Find algorithms in your program.
Theory Concept:
A Spanning tree is a subset to a connected graph G, where all the edges are connected, i.e, we can traverse to any
edge from a particular edge with or without intermediates. Also, a spanning tree must not have any cycle in it.
Thus, we can say that if there are n vertices in a connected graph then the no. of edges that a spanning tree may have
is n-1.
Implementation:
#include <stdio.h>
#include <stdlib.h>
struct Edge {
int src, dest, weight;
};
struct Subset {
int parent, rank;
};
struct Graph {
int V, E;
struct Edge* edges;
};
int main() {
int V = 4;
int E = 5;
struct Graph* graph = createGraph(V, E);
graph->edges[0].src = 0;
graph->edges[0].dest = 1;
graph->edges[0].weight = 10;
graph->edges[1].src = 0;
graph->edges[1].dest = 2;
graph->edges[1].weight = 6;
graph->edges[2].src = 0;
graph->edges[2].dest = 3;
graph->edges[2].weight = 5;
graph->edges[3].src = 1;
graph->edges[3].dest = 3;
graph->edges[3].weight = 15;
graph->edges[4].src = 2;
graph->edges[4].dest = 3;
graph->edges[4].weight = 4;
KruskalMST(graph);
return 0;
}
OUTPUT:
Experiment No. 16
Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s
algorithm
Theory Concept:
We have discussed Kruskal’s algorithm for Minimum Spanning Tree. Like Kruskal’s algorithm, Prim’s algorithm is
also a Greedy algorithm. It starts with an empty spanning tree. The idea is to maintain two sets of vertices. The first
set contains the vertices already included in the MST, the other set contains the vertices not yet included. At every
step, it considers all the edges that connect the two sets and picks the minimum weight edge from these edges. After
picking the edge, it moves the other endpoint of the edge to the set containing MST.
Implementation:
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 5
key[0] = 0;
parent[0] = -1;
int main() {
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
return 0;
}
OUTPUT:
Experiment No. 17
Theory Concept:
The all-pair shortest path algorithm is also known as Floyd-Warshall algorithm is used to find all pair shortest path
problem from a given weighted graph. As a result of this algorithm, it will generate a matrix, which will represent the
minimum distance from any node to all other nodes in the graph.
Travelling Salesman Problem (TSP): Given a set of cities and distances between every pair of cities, the problem is
to find the shortest possible route that visits every city exactly once and returns to the starting point. Note the difference
between Hamiltonian Cycle and TSP. The Hamiltonian cycle problem is to find if there exists a tour that visits every
city exactly once. Here we know that Hamiltonian Tour exists (because the graph is complete) and in fact, many such
tours exist, the problem is to find a minimum weight Hamiltonian Cycle. For example,
consider the graph shown in the figure on the right side. A TSP tour in the graph is 1-2-4-3-1 The cost of the tour is
10+25+30+15 which is 80. The problem is a famous NP-hard problem. There is no polynomial-time known solution
for this problem.
IMPLEMENTATION:
#include<iostream>
#include<iomanip>
#define NODE 7
#define INF 999
using namespace std;
int costMat[NODE][NODE] = {
{0, 3, 6, INF, INF, INF, INF},
{3, 0, 2, 1, INF, INF, INF},
{6, 2, 0, 1, 4, 2, INF},
{INF, 1, 1, 0, 2, INF, 4},
{INF, INF, 4, 2, 0, 2, 1},
{INF, INF, 2, INF, 2, 0, 1},
{INF, INF, INF, 4, 1, 1, 0}
};
void floydWarshal(){
int cost[NODE][NODE];
for(int i = 0; i < NODE; i++)
for(int j = 0; j < NODE; j++)
cost[i][j] = costMat[i][j];
int main(){
floydWarshal();
return 0;
}
OUTPUT:
Experiment No. 18
Design and implement 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}. Display a suitable message, if the given problem
instance doesn't have a solution
Theory Concept:
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal
to given sum.
Implementation:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(set) / sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
printf("Found a subset with the given sum\n");
else
printf("No subset with the given sum\n");
return 0;
}
OUTPUT:
Experiment No. 19
Design and implement to find all Hamiltonian Cycles in a connected undirected Graph G
of n vertices using backtracking principle
Theory Concept:
Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once. A Hamiltonian cycle (or
Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in the graph) from the last vertex to the first
vertex of the Hamiltonian Path. Determine whether a given graph contains Hamiltonian Cycle or not. If it contains,
then prints the path. Following are the input and output of the required function.
Implementation:
#include<stdio.h>
#define V 5
printSolution(path);
return true;
}
int main()
{
bool graph1[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0}};
hamCycle(graph1);
return 0;
}
OUTPUT: