Daa PR09 123
Daa PR09 123
PRACTICAL NO- 09
Theory:
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 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 print the path. Following are the input and output of the
required function.
Input:
A 2D array graph[V][V] where V is the number of vertices in graph and
graph[V][V] is adjacency matrix representation of the graph. A value graph[i][j]
is 1 if there is a direct edge from i to j, otherwise graph[i][j] is 0.
Output:
An array path[V] that should contain the Hamiltonian Path. path[i] should
represent the ith vertex in the Hamiltonian Path. The code should also return
false if there is no Hamiltonian Cycle in the graph.
For instance, when mapping genomes scientists must combine many tiny
fragments of genetic code (“reads”, they are called), into one single genomic
sequence (a ‘superstring’). This can be done by finding a Hamiltonian cycle or
Hamiltonian path, where each of the reads are considered nodes in a graph and
each overlap (place where the end of one read matches the beginning of
another) is considered to be an edge.
In a much less complex application of exactly the same math, school districts
use Hamiltonian cycles to plan the best route to pick up students from across
the district. Here students may be considered nodes, the paths between them
edges, and the bus wishes to travel a route that will pass each students house
exactly once.
Backtracking Algorithm for Hamiltonian cycle
Step1 : Create an empty path array and add vertex 0 to it.
Step 3: Before adding a vertex, check for whether it is adjacent to the previously
added vertex and not already added. If we find such a vertex, we add the vertex
as part of the solution.
Analysis :
Time complexity of the above algorithm is O(2nn2).
Code:
#include<iostream>
#define NODE 4
int graph[NODE][NODE];
int path[NODE];
cout << path[0] << endl; //print the first vertex again
}
bool isValid(int v, int k) {
return false;
for (int i = 0; i < k; i++) //if vertex is already taken, skip that
if (path[i] == v)
return false;
return true;
bool cycleFound(int k) {
if (graph[path[k-1]][ path[0] ] == 1 )
return true;
else
return false;
for (int v = 1; v < NODE; v++) { //for all vertices except starting point
path[k] = v;
return true;
}
return false;
bool hamiltonianCycle() {
path[i] = -1;
if ( cycleFound(1) == false ) {
return false;
displayCycle();
return true;
int main() {
int i,j;
for (i=0;i<NODE;i++){
for (j=0;j<NODE;j++){
cout << "Graph G(" << (i+1) << "," << (j+1) << ") = ";
for (i=0;i<NODE;i++){
for (j=0;j<NODE;j++){
hamiltonianCycle();
Output:
Conclusion :
In this practical we studied about Hamiltonian Cycle and implemented
Hamiltonian Cycle in C++ using Backtracking II