0% found this document useful (0 votes)
6 views48 pages

Department of Cse - Artificial Intelligence & Machine Learning

The document outlines a lab course for III B Tech II Sem students focusing on algorithms for efficient coding, with objectives to develop efficient coding for various algorithms and analyze their execution times. It includes a list of experiments involving algorithms such as Binary Search, Merge Sort, Quick Sort, and others, along with sample C code implementations and their time complexities. The course aims to enhance students' programming skills and understanding of algorithm efficiency through practical coding exercises.

Uploaded by

rajeshgantla18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views48 pages

Department of Cse - Artificial Intelligence & Machine Learning

The document outlines a lab course for III B Tech II Sem students focusing on algorithms for efficient coding, with objectives to develop efficient coding for various algorithms and analyze their execution times. It includes a list of experiments involving algorithms such as Binary Search, Merge Sort, Quick Sort, and others, along with sample C code implementations and their time complexities. The course aims to enhance students' programming skills and understanding of algorithm efficiency through practical coding exercises.

Uploaded by

rajeshgantla18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

DEPARTMENT OF CSE - ARTIFICIAL INTELLIGENCE & MACHINE LEARNING

III B Tech II Sem

ALGORITHMS FOR EFFICIENT CODING LAB

Course Objective:

To develop efficient coding for the algorithms with various inputs and algorithms

Course Outcomes:

By completing the course the students will be able to:

Analyze the program execution time

List of Experiments:

1. Develop a program and measure the running time for Binary Search with Divide and Conquer

2. Develop a program and measure the running time for Merge Sort with Divide and Conquer

3. Develop a program and measure the running time for Quick Sort with Divide and Conquer

4. Develop a program and measure the running time for estimating minimum-cost spanning
Trees with Greedy Method

5. Develop a program and measure the running time for estimating Single Source Shortest Paths
with Greedy Method

6. Develop a program and measure the running time for optimal Binary search trees with
Dynamic Programming

7. Develop a program and measure the running time for identifying solution for traveling
salesperson problem with Dynamic Programming

8. Develop a program and measure the running time for identifying solution for 8-Queens
problem with Backtracking

9. Develop a program and measure the running time for Graph Coloring with Backtracking

DAA Lab Manual


10. Develop a program and measure the running time to generate solution of Hamiltonian Cycle
problem with Backtracking

11. Develop a program and measure the running time running time to generate solution of
Knapsack problem with Backtracking

DAA Lab Manual


1. Develop a program and measure the running time for Binary Search with Divide and
Conquer

Time complexity:O(log n)

// Binary Search in C

#include <stdio.h>

int binarySearch(int array[], int x, int low, int high) {


// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;

if (array[mid] == x)
return mid;

if (array[mid] < x)
low = mid + 1;

else
high = mid - 1;
}

return -1;
}

int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}

DAA Lab Manual


2. Develop a program and measure the running time for Merge Sort with Divide and
Conquer

// Merge sort in C

#include <stdio.h>

// Merge two subarrays L and M into arr


void merge(int arr[], int p, int q, int r) {

// Create L ← A[p..q] and M ← A[q+1..r]


int n1 = q - p + 1;
int n2 = r - q;

int L[n1], M[n2];

for (int i = 0; i < n1; i++)


L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];

// Maintain current index of sub-arrays and main array


int i, j, k;
i = 0;
j = 0;
k = p;

// Until we reach either end of either L or M, pick larger among


// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}

DAA Lab Manual


// When we run out of elements in either L or M,
// pick up the remaining elements and put in A[p..r]
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = M[j];
j++;
k++;
}
}

// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {

// m is the point where the array is divided into two subarrays


int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted subarrays


merge(arr, l, m, r);
}
}

// Print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};

DAA Lab Manual


int size = sizeof(arr) / sizeof(arr[0]);

mergeSort(arr, 0, size - 1);

printf("Sorted array: \n");


printArray(arr, size);
}

Merge Sort Complexity

Time Complexity

Best O(n*log n)

Worst O(n*log n)

Average O(n*log n)

Space Complexity O(n)

Stability Yes

DAA Lab Manual


3. Develop a program and measure the running time for Quick Sort with Divide and
Conquer

// Quick sort in C

#include <stdio.h>

// function to swap elements


void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}

// function to find the partition position


int partition(int array[], int low, int high) {

// select the rightmost element as pivot


int pivot = array[high];

// pointer for greater element


int i = (low - 1);

// traverse each element of the array


// compare them with the pivot
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {

// if element smaller than pivot is found


// swap it with the greater element pointed by i
i++;

// swap element at i with element at j


swap(&array[i], &array[j]);
}
}

DAA Lab Manual


// swap the pivot element with the greater element at i
swap(&array[i + 1], &array[high]);

// return the partition point


return (i + 1);
}

void quickSort(int array[], int low, int high) {


if (low < high) {

// find the pivot element such that


// elements smaller than pivot are on left of pivot
// elements greater than pivot are on right of pivot
int pi = partition(array, low, high);

// recursive call on the left of pivot


quickSort(array, low, pi - 1);

// recursive call on the right of pivot


quickSort(array, pi + 1, high);
}
}

// function to print array elements


void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}

// main function
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};

int n = sizeof(data) / sizeof(data[0]);

printf("Unsorted Array\n");
printArray(data, n);

// perform quicksort on data

DAA Lab Manual


quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");


printArray(data, n);
}

Quicksort Complexity

Time Complexity

Best O(n*log n)

Worst O(n2)

Average O(n*log n)

Space Complexity O(log n)

Stability No

DAA Lab Manual


4. Develop a program and measure the running time for estimating minimum-cost
spanning Trees with Greedy Method

// Kruskal's algorithm in C

#include <stdio.h>

#define MAX 30

typedef struct edge {


int u, v, w;
} edge;

typedef struct edge_list {


edge data[MAX];
int n;
} edge_list;

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();

// Applying Krushkal Algo


void kruskalAlgo() {
int belongs[MAX], i, j, cno1, cno2;
elist.n = 0;

for (i = 1; i < n; i++)


for (j = 0; j < i; j++) {
if (Graph[i][j] != 0) {

DAA Lab Manual


elist.data[elist.n].u = i;
elist.data[elist.n].v = j;
elist.data[elist.n].w = Graph[i][j];
elist.n++;
}
}

sort();

for (i = 0; i < n; i++)


belongs[i] = i;

spanlist.n = 0;

for (i = 0; i < elist.n; i++) {


cno1 = find(belongs, elist.data[i].u);
cno2 = find(belongs, elist.data[i].v);

if (cno1 != cno2) {
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n = spanlist.n + 1;
applyUnion(belongs, cno1, cno2);
}
}
}

int find(int belongs[], int vertexno) {


return (belongs[vertexno]);
}

void applyUnion(int belongs[], int c1, int c2) {


int i;

for (i = 0; i < n; i++)


if (belongs[i] == c2)
belongs[i] = c1;
}

// Sorting algo
void sort() {
int i, j;

DAA Lab Manual


edge temp;

for (i = 1; i < elist.n; i++)


for (j = 0; j < elist.n - 1; j++)
if (elist.data[j].w > elist.data[j + 1].w) {
temp = elist.data[j];
elist.data[j] = elist.data[j + 1];
elist.data[j + 1] = temp;
}
}

// Printing the result


void print() {
int i, cost = 0;

for (i = 0; i < spanlist.n; i++) {


printf("\n%d - %d : %d", spanlist.data[i].u, spanlist.data[i].v, spanlist.data[i].w);
cost = cost + spanlist.data[i].w;
}

printf("\nSpanning tree cost: %d", cost);


}

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;

DAA Lab Manual


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;
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();
}

DAA Lab Manual


Kruskal's vs Prim's Algorithm

Prim's algorithm is another popular minimum spanning tree algorithm that uses a different logic
to find the MST of a graph. Instead of starting from an edge, Prim's algorithm starts from a
vertex and keeps adding lowest-weight edges which aren't in the tree, until all vertices have been
covered.

Kruskal's Algorithm Complexity

The time complexity Of Kruskal's Algorithm is: O(E log E).

DAA Lab Manual


5. Develop a program and measure the running time for estimating Single Source Shortest
Paths with Greedy Method

/ C program for Dijkstra's single source shortest path


// algorithm. The program is for adjacency matrix
// representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

// Number of vertices in the graph


#define V 9

// A utility function to find the vertex with minimum


// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

// A utility function to print the constructed distance


// array
void printSolution(int dist[])

DAA Lab Manual


{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}

// Function that implements Dijkstra's single source


// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the
// shortest
// distance from src to i

bool sptSet[V]; // sptSet[i] will be true if vertex i is


// included in shortest
// path tree or shortest distance from src to i is
// finalized

// Initialize all distances as INFINITE and stpSet[] as


// false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
// vertices not yet processed. u is always equal to
// src in the first iteration.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the


// picked vertex.
for (int v = 0; v < V; v++)

DAA Lab Manual


// Update dist[v] only if is not in sptSet,
// there is an edge from u to v, and total
// weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

// print the constructed distance array


printSolution(dist);
}

// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

// Function call
dijkstra(graph, 0);

return 0;
}

DAA Lab Manual


6. Develop a program and measure the running time for optimal Binary search trees with
Dynamic Programming

// A naive recursive implementation of optimal binary

// search tree problem

#include <stdio.h>

#include <limits.h>

// A utility function to get sum of array elements

// freq[i] to freq[j]

int sum(int freq[], int i, int j);

// A recursive function to calculate cost of optimal

// binary search tree

int optCost(int freq[], int i, int j)

DAA Lab Manual


{

// Base cases

if (j < i) // no elements in this subarray

return 0;

if (j == i) // one element in this subarray

return freq[i];

// Get sum of freq[i], freq[i+1], ... freq[j]

int fsum = sum(freq, i, j);

// Initialize minimum value

int min = INT_MAX;

// One by one consider all elements as root and

// recursively find cost of the BST, compare the

// cost with min and update min if needed

for (int r = i; r <= j; ++r)

DAA Lab Manual


{

int cost = optCost(freq, i, r-1) +

optCost(freq, r+1, j);

if (cost < min)

min = cost;

// Return minimum value

return min + fsum;

// The main function that calculates minimum cost of

// a Binary Search Tree. It mainly uses optCost() to

// find the optimal cost.

int optimalSearchTree(int keys[], int freq[], int n)

// Here array keys[] is assumed to be sorted in

DAA Lab Manual


// increasing order. If keys[] is not sorted, then

// add code to sort keys, and rearrange freq[]

// accordingly.

return optCost(freq, 0, n-1);

// A utility function to get sum of array elements

// freq[i] to freq[j]

int sum(int freq[], int i, int j)

int s = 0;

for (int k = i; k <=j; k++)

s += freq[k];

return s;

// Driver program to test above functions

DAA Lab Manual


int main()

int keys[] = {10, 12, 20};

int freq[] = {34, 8, 50};

int n = sizeof(keys)/sizeof(keys[0]);

printf("Cost of Optimal BST is %d ",

optimalSearchTree(keys, freq, n));

return 0;

Output
Cost of Optimal BST is 142

DAA Lab Manual


7. Develop a program and measure the running time for identifying solution for traveling
salesperson problem with Dynamic Programming

#include <stdio.h>

int ary[10][10], completed[10], n, cost = 0;

void mincost(int city) {


int i, ncity;

completed[city] = 1;

//printf("%d--->", city + 1);


ncity = least(city);

if (ncity == 999) {
ncity = 0;
printf("%d", ncity + 1);
cost += ary[city][ncity];

return;
}

mincost(ncity);
}

int least(int c) {
int i, nc = 999;
int min = 999, kmin;

for (i = 0; i < n; i++) {


if ((ary[c][i] != 0) && (completed[i] == 0))

DAA Lab Manual


if (ary[c][i] + ary[i][c] < min) {
min = ary[i][0] + ary[c][i];
kmin = ary[c][i];
nc = i;
}
}

if (min != 999)
cost += kmin;

return nc;
}

int main() {
int n = 4;
ary[0][0] = 0;
ary[0][1] = 4;
ary[0][2] = 1;
ary[1][0] = 4;
ary[1][1] = 0;
ary[1][2] = 2;
ary[2][0] = 1;
ary[2][1] = 2;
ary[2][1] = 0;

int i;
for(i = 0 ; i < n; i++){
completed[i] = 0;
}
mincost(0);
printf("%d", cost);
return 0;
}

DAA Lab Manual


8. Develop a program and measure the running time for identifying solution for 8-Queens
problem with Backtracking

#include<stdio.h>
#include<math.h>

void queen(int row, int p);


int chess[8],count;

int main()/*from w w w . j ava2 s. c o m*/


{
int p = 8;
queen(1,p);
return 0;
}

void print(int p)
{
int i,j;
printf("\n\nThis is Solution no. %d:\n\n",++count);
for(i=1;i<=p;++i)

DAA Lab Manual


printf("\t%d",i);

for(i=1;i<=p;++i){
printf("\n\n%d",i);
for(j=1;j<=p;++j){
if(chess[i]==j)
printf("\tQ");
else
printf("\t-");
}
}
printf("\n\n\nThere are total 92 solutions for 8-queens problem.");
}

int place(int row,int column)


{
int i;
for(i=1;i<=row-1;++i)
{
if(chess[i]==column)
return 0;
else
if(abs(chess[i]-column)==abs(i-row))
return 0;
}

DAA Lab Manual


return 1;
}

void queen(int row,int p)


{
int column;
for(column=1;column<=p;++column)
{
if(place(row,column))
{
chess[row]=column;
if(row==p)
print(p);
else
queen(row+1,p);
}
}
}

Result

DAA Lab Manual


9. Develop a program and measure the running time for Graph Coloring with
Backtracking

// C program for the above approach

#include <stdbool.h>

#include <stdio.h>

// Number of vertices in the graph

DAA Lab Manual


#define V 4

void printSolution(int color[]);

// check if the colored

// graph is safe or not

bool isSafe(bool graph[V][V], int color[])

// check for every edge

for (int i = 0; i < V; i++)

for (int j = i + 1; j < V; j++)

if (graph[i][j] && color[j] == color[i])

return false;

return true;

/* This function solves the m Coloring

DAA Lab Manual


problem using recursion. It returns

false if the m colours cannot be assigned,

otherwise, return true and prints

assignments of colours to all vertices.

Please note that there may be more than

one solutions, this function prints one

of the feasible solutions.*/

bool graphColoring(bool graph[V][V], int m, int i,

int color[V])

// if current index reached end

if (i == V) {

// if coloring is safe

if (isSafe(graph, color)) {

// Print the solution

printSolution(color);

return true;

DAA Lab Manual


}

return false;

// Assign each color from 1 to m

for (int j = 1; j <= m; j++) {

color[i] = j;

// Recur of the rest vertices

if (graphColoring(graph, m, i + 1, color))

return true;

color[i] = 0;

return false;

DAA Lab Manual


/* A utility function to print solution */

void printSolution(int color[])

printf("Solution Exists:"

" Following are the assigned colors \n");

for (int i = 0; i < V; i++)

printf(" %d ", color[i]);

printf("\n");

// Driver code

int main()

/* Create following graph and

test whether it is 3 colorable

(3)---(2)

DAA Lab Manual


| /|

| / |

|/ |

(0)---(1)

*/

bool graph[V][V] = {

{ 0, 1, 1, 1 },

{ 1, 0, 1, 0 },

{ 1, 1, 0, 1 },

{ 1, 0, 1, 0 },

};

int m = 3; // Number of colors

// Initialize all color values as 0.

// This initialization is needed

// correct functioning of isSafe()

int color[V];

DAA Lab Manual


for (int i = 0; i < V; i++)

color[i] = 0;

// Function call

if (!graphColoring(graph, m, 0, color))

printf("Solution does not exist");

return 0;

Output
Solution Exists: Following are the assigned colors
1 2 3 2
Time Complexity: O(mV). There is a total O(m V) combination of colors
Auxiliary Space: O(V). Recursive Stack of graph coloring(…) function will require O(V)
space.

DAA Lab Manual


10. Develop a program and measure the running time to generate solution of Hamiltonian
Cycle problem with Backtracking

/* C program for solution of Hamiltonian Cycle problem

using backtracking */

#include<stdio.h>

// Number of vertices in the graph

#define V 5

DAA Lab Manual


void printSolution(int path[]);

/* A utility function to check if the vertex v can be added at

index 'pos' in the Hamiltonian Cycle constructed so far (stored

in 'path[]') */

bool isSafe(int v, bool graph[V][V], int path[], int pos)

/* Check if this vertex is an adjacent vertex of the previously

added vertex. */

if (graph [ path[pos-1] ][ v ] == 0)

return false;

/* Check if the vertex has already been included.

This step can be optimized by creating an array of size V */

for (int i = 0; i < pos; i++)

DAA Lab Manual


if (path[i] == v)

return false;

return true;

/* A recursive utility function to solve hamiltonian cycle problem */

bool hamCycleUtil(bool graph[V][V], int path[], int pos)

/* base case: If all vertices are included in Hamiltonian Cycle */

if (pos == V)

// And if there is an edge from the last included vertex to the

// first vertex

if ( graph[ path[pos-1] ][ path[0] ] == 1 )

return true;

DAA Lab Manual


else

return false;

// Try different vertices as a next candidate in Hamiltonian Cycle.

// We don't try for 0 as we included 0 as starting point in hamCycle()

for (int v = 1; v < V; v++)

/* Check if this vertex can be added to Hamiltonian Cycle */

if (isSafe(v, graph, path, pos))

path[pos] = v;

/* recur to construct rest of the path */

if (hamCycleUtil (graph, path, pos+1) == true)

return true;

DAA Lab Manual


/* If adding vertex v doesn't lead to a solution,

then remove it */

path[pos] = -1;

/* If no vertex can be added to Hamiltonian Cycle constructed so far,

then return false */

return false;

/* This function solves the Hamiltonian Cycle problem using Backtracking.

It mainly uses hamCycleUtil() to solve the problem. It returns false

if there is no Hamiltonian Cycle possible, otherwise return true and

prints the path. Please note that there may be more than one solutions,

DAA Lab Manual


this function prints one of the feasible solutions. */

bool hamCycle(bool graph[V][V])

int *path = new int[V];

for (int i = 0; i < V; i++)

path[i] = -1;

/* Let us put vertex 0 as the first vertex in the path. If there is

a Hamiltonian Cycle, then the path can be started from any point

of the cycle as the graph is undirected */

path[0] = 0;

if ( hamCycleUtil(graph, path, 1) == false )

printf("\nSolution does not exist");

return false;

DAA Lab Manual


printSolution(path);

return true;

/* A utility function to print solution */

void printSolution(int path[])

printf ("Solution Exists:"

" Following is one Hamiltonian Cycle \n");

for (int i = 0; i < V; i++)

printf(" %d ", path[i]);

// Let us print the first vertex again to show the complete cycle

printf(" %d ", path[0]);

printf("\n");

DAA Lab Manual


}

// driver program to test above function

int main()

/* Let us create the following graph

(0)--(1)--(2)

| /\ |

| / \ |

|/ \|

(3)-------(4) */

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},

DAA Lab Manual


};

// Print the solution

hamCycle(graph1);

/* Let us create the following graph

(0)--(1)--(2)

| /\ |

| / \ |

|/ \|

(3) (4) */

bool graph2[V][V] = {{0, 1, 0, 1, 0},

{1, 0, 1, 1, 1},

{0, 1, 0, 0, 1},

{1, 1, 0, 0, 0},

{0, 1, 1, 0, 0},

DAA Lab Manual


};

// Print the solution

hamCycle(graph2);

return 0;

Output:
Solution Exists: Following is one Hamiltonian Cycle
0 1 2 4 3 0

Solution does not exist


Time Complexity : O(N!), where N is number of vertices.
Auxiliary Space : O(1), since no extra space used.

DAA Lab Manual


11. Develop a program and measure the running time running time to generate solution of
Knapsack problem with Backtracking

* A Naive recursive implementation

of 0-1 Knapsack problem */

#include <stdio.h>

// A utility function that returns

DAA Lab Manual


// maximum of two integers

int max(int a, int b) { return (a > b) ? a : b; }

// Returns the maximum value that can be

// put in a knapsack of capacity W

int knapSack(int W, int wt[], int val[], int n)

// Base Case

if (n == 0 || W == 0)

return 0;

// If weight of the nth item is more than

// Knapsack capacity W, then this item cannot

// be included in the optimal solution

if (wt[n - 1] > W)

return knapSack(W, wt, val, n - 1);

DAA Lab Manual


// Return the maximum of two cases:

// (1) nth item included

// (2) not included

else

return max(

val[n - 1]

+ knapSack(W - wt[n - 1], wt, val, n - 1),

knapSack(W, wt, val, n - 1));

// Driver code

int main()

int val[] = { 60, 100, 120 };

int wt[] = { 10, 20, 30 };

int W = 50;

int n = sizeof(val) / sizeof(val[0]);

DAA Lab Manual


printf("%d", knapSack(W, wt, val, n));

return 0;

Output
220
Time Complexity: O(2N)
Auxiliary Space: O(N), Stack space required for recursion

DAA Lab Manual

You might also like