0% found this document useful (0 votes)
61 views51 pages

Assignment Analysis Design of Algorithm Anshika Chauhan 0103CS191041

The document contains instructions for 5 programming assignments: 1. Write programs for iterative and recursive binary search on an integer array. 2. Write a program to implement merge sort on an integer array. 3. Write a program to implement quicksort on an integer array. 4. Write a program to calculate the minimum number of computations required to merge a given set of file sizes using optimal merge patterns. 5. Write a program to implement Huffman coding to compress data.

Uploaded by

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

Assignment Analysis Design of Algorithm Anshika Chauhan 0103CS191041

The document contains instructions for 5 programming assignments: 1. Write programs for iterative and recursive binary search on an integer array. 2. Write a program to implement merge sort on an integer array. 3. Write a program to implement quicksort on an integer array. 4. Write a program to calculate the minimum number of computations required to merge a given set of file sizes using optimal merge patterns. 5. Write a program to implement Huffman coding to compress data.

Uploaded by

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

ASSIGNMENT

Analysis Design of Algorithm

ANSHIKA CHAUHAN
0103CS191041

1. Write a program for Iterative and Recursive Binary Search.

Iterative:
int binarySearch(int arr[], int l, int r, int x)

while (l <= r)

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

// Check if x is present at mid

if (arr[m] == x)

return m;

// If x greater, ignore left half

if (arr[m] < x)

l = m + 1;

// If x is smaller, ignore right half

else

r = m - 1;

// if we reach here, then element was not present


return -1;

int main(void)

int arr[] = {2, 3, 4, 10, 40};

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

int x = 10;

int result = binarySearch(arr, 0, n-1, x);

(result == -1)? printf("Element is not present in array")

: printf("Element is present at index %d", result);

return 0;

Recursive:
#include <stdio.h>

// A recursive binary search function. It returns location of x in

// given array arr[l..r] is present, otherwise -1

int binarySearch(int arr[], int l, int r, int x)

if (r >= l)

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

// If the element is present at the middle itself

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


// If element is smaller than mid, then it can only be present

// in left subarray

if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);

// Else the element can only be present in right subarray

return binarySearch(arr, mid+1, r, x);

// We reach here when element is not present in array

return -1;

int main(void)

int arr[] = {2, 3, 4, 10, 40};

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

int x = 10;

int result = binarySearch(arr, 0, n-1, x);

(result == -1)? printf("Element is not present in array")

: printf("Element is present at index %d", result);

return 0;

2. Write a program for Merge Sort.


#include <iostream>
using namespace std;

// Merges two subarrays of array[].

// First subarray is arr[begin..mid]

// Second subarray is arr[mid+1..end]

void merge(int array[], int const left, int const mid, int const right)

auto const subArrayOne = mid - left + 1;

auto const subArrayTwo = right - mid;

// Create temp arrays

auto *leftArray = new int[subArrayOne],

*rightArray = new int[subArrayTwo];

// Copy data to temp arrays leftArray[] and rightArray[]

for (auto i = 0; i < subArrayOne; i++)

leftArray[i] = array[left + i];

for (auto j = 0; j < subArrayTwo; j++)

rightArray[j] = array[mid + 1 + j];

auto indexOfSubArrayOne = 0, // Initial index of first sub-array

indexOfSubArrayTwo = 0; // Initial index of second sub-array

int indexOfMergedArray = left; // Initial index of merged array

// Merge the temp arrays back into array[left..right]


while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo < subArrayTwo) {

if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) {

array[indexOfMergedArray] = leftArray[indexOfSubArrayOne];

indexOfSubArrayOne++;

else {

array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo];

indexOfSubArrayTwo++;

indexOfMergedArray++;

// Copy the remaining elements of

// left[], if there are any

while (indexOfSubArrayOne < subArrayOne) {

array[indexOfMergedArray] = leftArray[indexOfSubArrayOne];

indexOfSubArrayOne++;

indexOfMergedArray++;

// Copy the remaining elements of

// left[], if there are any

while (indexOfSubArrayTwo < subArrayTwo) {

array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo];

indexOfSubArrayTwo++;

indexOfMergedArray++;
}

// begin is for left index and end is

// right index of the sub-array

// of arr to be sorted */

void mergeSort(int array[], int const begin, int const end)

if (begin >= end)

return; // Returns recursivly

auto mid = begin + (end - begin) / 2;

mergeSort(array, begin, mid);

mergeSort(array, mid + 1, end);

merge(array, begin, mid, end);

// UTILITY FUNCTIONS

// Function to print an array

void printArray(int A[], int size)

for (auto i = 0; i < size; i++)

cout << A[i] << " ";

}
3. Write a program for Quick Sort.
#include <bits/stdc++.h>

using namespace std;

// A utility function to swap two elements

void swap(int* a, int* b)

int t = *a;

*a = *b;

*b = t;

/* This function takes last element as pivot, places

the pivot element at its correct position in sorted

array, and places all smaller (smaller than pivot)

to left of pivot and all greater elements to right

of pivot */

int partition (int arr[], int low, int high)

int pivot = arr[high]; // pivot

int i = (low - 1); // Index of smaller element and indicates the right position of pivot found so
far
for (int j = low; j <= high - 1; j++)

// If current element is smaller than the pivot

if (arr[j] < pivot)

i++; // increment index of smaller element

swap(&arr[i], &arr[j]);

swap(&arr[i + 1], &arr[high]);

return (i + 1);

/* The main function that implements QuickSort

arr[] --> Array to be sorted,

low --> Starting index,

high --> Ending index */

void quickSort(int arr[], int low, int high)

if (low < high)

/* pi is partitioning index, arr[p] is now

at right place */

int pi = partition(arr, low, high);


// Separately sort elements before

// partition and after partition

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

/* Function to print an array */

void printArray(int arr[], int size)

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

cout << arr[i] << " ";

cout << endl;

4. Write a program for optimal merge patterns.


#include<bits/stdc++.h>

using namespace std;

// Function to find minimum computation

int minComputation(int size, int files[])

{
// Create a min heap

priority_queue<int, vector<int>,

greater<int>> pq;

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

// Add sizes to priorityQueue

pq.push(files[i]);

// Variable to count total Computation

int count = 0;

while(pq.size() > 1)

// pop two smallest size element

// from the min heap

int first_smallest = pq.top();

pq.pop();

int second_smallest = pq.top();

pq.pop();
int temp = first_smallest + second_smallest;

// Add the current computations

// with the previous one's

count += temp;

// Add new combined file size

// to priority queue or min heap

pq.push(temp);

return count;

// Driver code

int main()

// No of files

int n = 6;

// 6 files with their sizes

int files[] = { 2, 3, 4, 5, 6, 7 };
// Total no of computations

// do be done final answer

cout << "Minimum Computations = "

<< minComputation(n, files);

return 0;

5. Write a program for Huffman coding.


#include <stdio.h>

#include <stdlib.h>

// This constant can be avoided by explicitly

// calculating height of Huffman Tree

#define MAX_TREE_HT 100

// A Huffman tree node

struct MinHeapNode {

// One of the input characters

char data;

// Frequency of the character

unsigned freq;
// Left and right child of this node

struct MinHeapNode *left, *right;

};

// A Min Heap: Collection of

// min-heap (or Huffman tree) nodes

struct MinHeap {

// Current size of min heap

unsigned size;

// capacity of min heap

unsigned capacity;

// Array of minheap node pointers

struct MinHeapNode** array;

};

// A utility function allocate a new

// min heap node with given character

// and frequency of the character

struct MinHeapNode* newNode(char data, unsigned freq)

{
struct MinHeapNode* temp = (struct MinHeapNode*)malloc(

sizeof(struct MinHeapNode));

temp->left = temp->right = NULL;

temp->data = data;

temp->freq = freq;

return temp;

// A utility function to create

// a min heap of given capacity

struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap

= (struct MinHeap*)malloc(sizeof(struct MinHeap));

// current size is 0

minHeap->size = 0;

minHeap->capacity = capacity;
minHeap->array = (struct MinHeapNode**)malloc(

minHeap->capacity * sizeof(struct MinHeapNode*));

return minHeap;

// A utility function to

// swap two min heap nodes

void swapMinHeapNode(struct MinHeapNode** a,

struct MinHeapNode** b)

struct MinHeapNode* t = *a;

*a = *b;

*b = t;

// The standard minHeapify function.

void minHeapify(struct MinHeap* minHeap, int idx)

int smallest = idx;

int left = 2 * idx + 1;


int right = 2 * idx + 2;

if (left < minHeap->size

&& minHeap->array[left]->freq

< minHeap->array[smallest]->freq)

smallest = left;

if (right < minHeap->size

&& minHeap->array[right]->freq

< minHeap->array[smallest]->freq)

smallest = right;

if (smallest != idx) {

swapMinHeapNode(&minHeap->array[smallest],

&minHeap->array[idx]);

minHeapify(minHeap, smallest);

// A utility function to check

// if size of heap is 1 or not

int isSizeOne(struct MinHeap* minHeap)

{
return (minHeap->size == 1);

// A standard function to extract

// minimum value node from heap

struct MinHeapNode* extractMin(struct MinHeap* minHeap)

struct MinHeapNode* temp = minHeap->array[0];

minHeap->array[0] = minHeap->array[minHeap->size - 1];

--minHeap->size;

minHeapify(minHeap, 0);

return temp;

// A utility function to insert

// a new node to Min Heap

void insertMinHeap(struct MinHeap* minHeap,

struct MinHeapNode* minHeapNode)

{
++minHeap->size;

int i = minHeap->size - 1;

while (i

&& minHeapNode->freq

< minHeap->array[(i - 1) / 2]->freq) {

minHeap->array[i] = minHeap->array[(i - 1) / 2];

i = (i - 1) / 2;

minHeap->array[i] = minHeapNode;

// A standard function to build min heap

void buildMinHeap(struct MinHeap* minHeap)

int n = minHeap->size - 1;

int i;

for (i = (n - 1) / 2; i >= 0; --i)


minHeapify(minHeap, i);

// A utility function to print an array of size n

void printArr(int arr[], int n)

int i;

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

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

printf("\n");

// Utility function to check if this node is leaf

int isLeaf(struct MinHeapNode* root)

return !(root->left) && !(root->right);

// Creates a min heap of capacity

// equal to size and inserts all character of

// data[] in min heap. Initially size of


// min heap is equal to capacity

struct MinHeap* createAndBuildMinHeap(char data[],

int freq[], int size)

struct MinHeap* minHeap = createMinHeap(size);

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

minHeap->array[i] = newNode(data[i], freq[i]);

minHeap->size = size;

buildMinHeap(minHeap);

return minHeap;

// The main function that builds Huffman tree

struct MinHeapNode* buildHuffmanTree(char data[],

int freq[], int size)

struct MinHeapNode *left, *right, *top;


// Step 1: Create a min heap of capacity

// equal to size. Initially, there are

// modes equal to size.

struct MinHeap* minHeap

= createAndBuildMinHeap(data, freq, size);

// Iterate while size of heap doesn't become 1

while (!isSizeOne(minHeap)) {

// Step 2: Extract the two minimum

// freq items from min heap

left = extractMin(minHeap);

right = extractMin(minHeap);

// Step 3: Create a new internal

// node with frequency equal to the

// sum of the two nodes frequencies.

// Make the two extracted node as

// left and right children of this new node.

// Add this node to the min heap

// '$' is a special value for internal nodes, not

// used

top = newNode('$', left->freq + right->freq);


top->left = left;

top->right = right;

insertMinHeap(minHeap, top);

// Step 4: The remaining node is the

// root node and the tree is complete.

return extractMin(minHeap);

// Prints huffman codes from the root of Huffman Tree.

// It uses arr[] to store codes

void printCodes(struct MinHeapNode* root, int arr[],

int top)

// Assign 0 to left edge and recur

if (root->left) {

arr[top] = 0;

printCodes(root->left, arr, top + 1);

}
// Assign 1 to right edge and recur

if (root->right) {

arr[top] = 1;

printCodes(root->right, arr, top + 1);

// If this is a leaf node, then

// it contains one of the input

// characters, print the character

// and its code from arr[]

if (isLeaf(root)) {

printf("%c: ", root->data);

printArr(arr, top);

// The main function that builds a

// Huffman Tree and print codes by traversing

// the built Huffman Tree

void HuffmanCodes(char data[], int freq[], int size)


{

// Construct Huffman Tree

struct MinHeapNode* root

= buildHuffmanTree(data, freq, size);

// Print Huffman codes using

// the Huffman tree built above

int arr[MAX_TREE_HT], top = 0;

printCodes(root, arr, top);

// Driver code

int main()

char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

int freq[] = { 5, 9, 12, 13, 16, 45 };

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

HuffmanCodes(arr, freq, size);

return 0;
}
6. Write a program for minimum spanning trees using Kruskal’s algorithm.
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// a structure to represent a weighted edge in graph

struct Edge {

int src, dest, weight;

};

// a structure to represent a connected, undirected

// and weighted graph

struct Graph {

// V-> Number of vertices, E-> Number of edges

int V, E;

// graph is represented as an array of edges.

// Since the graph is undirected, the edge

// from src to dest is also edge from dest

// to src. Both are counted as 1 edge here.

struct Edge* edge;

};

// Creates a graph with V vertices and E edges


struct Graph* createGraph(int V, int E)

struct Graph* graph = (struct Graph*)(malloc(sizeof(struct Graph)));

graph->V = V;

graph->E = E;

graph->edge = (struct Edge*)malloc(sizeof( struct Edge));

return graph;

// A structure to represent a subset for union-find

struct subset {

int parent;

int rank;

};

// A utility function to find set of an element i

// (uses path compression technique)

int find(struct subset subsets[], int i)

// find root and make root as parent of i

// (path compression)

if (subsets[i].parent != i)
subsets[i].parent

= find(subsets, subsets[i].parent);

return subsets[i].parent;

// A function that does union of two sets of x and y

// (uses union by rank)

void Union(struct subset subsets[], int x, int y)

int xroot = find(subsets, x);

int yroot = find(subsets, y);

// Attach smaller rank tree under root of high

// rank tree (Union by Rank)

if (subsets[xroot].rank < subsets[yroot].rank)

subsets[xroot].parent = yroot;

else if (subsets[xroot].rank > subsets[yroot].rank)

subsets[yroot].parent = xroot;

// If ranks are same, then make one as root and

// increment its rank by one

else

{
subsets[yroot].parent = xroot;

subsets[xroot].rank++;

// Compare two edges according to their weights.

// Used in qsort() for sorting an array of edges

int myComp(const void* a, const void* b)

struct Edge* a1 = (struct Edge*)a;

struct Edge* b1 = (struct Edge*)b;

return a1->weight > b1->weight;

// The main function to construct MST using Kruskal's

// algorithm

void KruskalMST(struct Graph* graph)

int V = graph->V;

struct Edge

result[V]; // Tnis will store the resultant MST

int e = 0; // An index variable, used for result[]

int i = 0; // An index variable, used for sorted edges


// Step 1: Sort all the edges in non-decreasing

// order of their weight. If we are not allowed to

// change the given graph, we can create a copy of

// array of edges

qsort(graph->edge, graph->E, sizeof(graph->edge[0]),

myComp);

// Allocate memory for creating V ssubsets

struct subset* subsets

= (struct subset*)malloc(V * sizeof(struct subset));

// Create V subsets with single elements

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

subsets[v].parent = v;

subsets[v].rank = 0;

// Number of edges to be taken is equal to V-1

while (e < V - 1 && i < graph->E) {

// Step 2: Pick the smallest edge. And increment

// the index for next iteration

struct Edge next_edge = graph->edge[i++];

int x = find(subsets, next_edge.src);


int y = find(subsets, next_edge.dest);

// If including this edge does't cause cycle,

// include it in result and increment the index

// of result for next edge

if (x != y) {

result[e++] = next_edge;

Union(subsets, x, y);

// Else discard the next_edge

// print the contents of result[] to display the

// built MST

printf(

"Following are the edges in the constructed MST\n");

int minimumCost = 0;

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

printf("%d -- %d == %d\n", result[i].src,

result[i].dest, result[i].weight);

minimumCost += result[i].weight;

printf("Minimum Cost Spanning tree : %d",minimumCost);


return;

// Driver program to test above functions

int main()

/* Let us create following weighted graph

10

0--------1

|\ |

6| 5\ |15

| \|

2--------3

4 */

int V = 4; // Number of vertices in graph

int E = 5; // Number of edges in graph

struct Graph* graph = createGraph(V, E);

// add edge 0-1

graph->edge[0].src = 0;

graph->edge[0].dest = 1;

graph->edge[0].weight = 10;

// add edge 0-2


graph->edge[1].src = 0;

graph->edge[1].dest = 2;

graph->edge[1].weight = 6;

// add edge 0-3

graph->edge[2].src = 0;

graph->edge[2].dest = 3;

graph->edge[2].weight = 5;

// add edge 1-3

graph->edge[3].src = 1;

graph->edge[3].dest = 3;

graph->edge[3].weight = 15;

// add edge 2-3

graph->edge[4].src = 2;

graph->edge[4].dest = 3;

graph->edge[4].weight = 4;

KruskalMST(graph);

return 0;

}
7. Write a program for minimum spanning trees using Prim’s algorithm.
#include <bits/stdc++.h>

using namespace std;

// Number of vertices in the graph

#define V 5

// A utility function to find the vertex with

// minimum key value, from the set of vertices

// not yet included in MST

int minKey(int key[], bool mstSet[])

// Initialize min value

int min = INT_MAX, min_index;

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

if (mstSet[v] == false && key[v] < min)

min = key[v], min_index = v;

return min_index;

// A utility function to print the

// constructed MST stored in parent[]


void printMST(int parent[], int graph[V][V])

cout<<"Edge \tWeight\n";

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

cout<<parent[i]<<" - "<<i<<" \t"<<graph[i][parent[i]]<<" \n";

// Function to construct and print MST for

// a graph represented using adjacency

// matrix representation

void primMST(int graph[V][V])

// Array to store constructed MST

int parent[V];

// Key values used to pick minimum weight edge in cut

int key[V];

// To represent set of vertices included in MST

bool mstSet[V];

// Initialize all keys as INFINITE

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

key[i] = INT_MAX, mstSet[i] = false;


// Always include first 1st vertex in MST.

// Make key 0 so that this vertex is picked as first vertex.

key[0] = 0;

parent[0] = -1; // First node is always root of MST

// The MST will have V vertices

for (int count = 0; count < V - 1; count++)

// Pick the minimum key vertex from the

// set of vertices not yet included in MST

int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set

mstSet[u] = true;

// Update key value and parent index of

// the adjacent vertices of the picked vertex.

// Consider only those vertices which are not

// yet included in MST

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

// graph[u][v] is non zero only for adjacent vertices of m

// mstSet[v] is false for vertices not yet included in MST


// Update the key only if graph[u][v] is smaller than key[v]

if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])

parent[v] = u, key[v] = graph[u][v];

// print the constructed MST

printMST(parent, graph);

8. Write a program for single sources shortest path algorithm.


#include<stdio.h>

#include<conio.h>

#define INFINITY 9999

#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()

clrscr();

int G[MAX][MAX],i,j,n,u;

printf("Enter no. of vertices:");

scanf("%d",&n);

printf("\nEnter the adjacency matrix:\n");


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

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

scanf("%d",&G[i][j]);

printf("\nEnter the starting node:");

scanf("%d",&u);

dijkstra(G,n,u);

getch();

return 0;

void dijkstra(int G[MAX][MAX],int n,int startnode)

int cost[MAX][MAX],distance[MAX],pred[MAX];

int visited[MAX],count,mindistance,nextnode,i,j;

//pred[] stores the predecessor of each node

//count gives the number of nodes seen so far


//create the cost matrix

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

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

{ if(G[i][j]==0)

cost[i][j]=INFINITY;

else

cost[i][j]=G[i][j];

//initialize pred[],distance[] and visited[]

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

distance[i]=cost[startnode][i];
pred[i]=startnode;

visited[i]=0;

distance[startnode]=0;

visited[startnode]=1;

count=1;

while(count<n-1)

mindistance=INFINITY;

//nextnode gives the node at minimum distance

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

if(distance[i]<mindistance&&!visited[i])
{

mindistance=distance[i];

nextnode=i;

//check if a better path exists through nextnode

visited[nextnode]=1;

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

if(!visited[i])

if(mindistance+cost[nextnode][i]<distance[i])

distance[i]=mindistance+cost[nextnode][i];

pred[i]=nextnode;
}

count++;

//print the path and distance of each node

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

if(i!=startnode)

printf("\nDistance of node%d=%d",i,distance[i]);

printf("\nPath=%d",i);

j=i;

do

{
j=pred[j];

printf("<-%d",j);

}while(j!=startnode);

9. Write a program for traveling salesman problem.


#include <bits/stdc++.h>

using namespace std;

#define V 4

// implementation of traveling Salesman Problem

int travllingSalesmanProblem(int graph[][V], int s)

// store all vertex apart from source vertex

vector<int> vertex;

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

if (i != s)

vertex.push_back(i);
// store minimum weight Hamiltonian Cycle.

int min_path = INT_MAX;

do {

// store current Path weight(cost)

int current_pathweight = 0;

// compute current path weight

int k = s;

for (int i = 0; i < vertex.size(); i++) {

current_pathweight += graph[k][vertex[i]];

k = vertex[i];

current_pathweight += graph[k][s];

// update minimum

min_path = min(min_path, current_pathweight);

} while (

next_permutation(vertex.begin(), vertex.end()));

return min_path;

}
// Driver Code

int main()

// matrix representation of graph

int graph[][V] = { { 0, 10, 15, 20 },

{ 10, 0, 35, 25 },

{ 15, 35, 0, 30 },

{ 20, 25, 30, 0 } };

int s = 0;

cout << travllingSalesmanProblem(graph, s) << endl;

return 0;

10. Write a program for Hamiltonian cycle problem.


#include <bits/stdc++.h>

using namespace std;

// Number of vertices in the graph

#define V 5

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++)

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;

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;

/* 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, 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 )

cout << "\nSolution does not exist";

return false;

printSolution(path);

return true;

/* A utility function to print solution */

void printSolution(int path[])

cout << "Solution Exists:"

" Following is one Hamiltonian Cycle \n";


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

cout << path[i] << " ";

// Let us print the first vertex again

// to show the complete cycle

cout << path[0] << " ";

cout << endl;

// Driver Code

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}};
// 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}};

// Print the solution

hamCycle(graph2);

return 0;

You might also like