What is Hamiltonian Cycle?
Hamiltonian Cycle or Circuit in a graph G is a cycle that visits every vertex of G exactly once and returns to the starting vertex.
- If graph contains a Hamiltonian cycle, it is called Hamiltonian graph otherwise it is non-Hamiltonian.
- Finding a Hamiltonian Cycle in a graph is a well-known NP-complete problem, which means that there’s no known efficient algorithm to solve it for all types of graphs. However, it can be solved for small or specific types of graphs.
The Hamiltonian Cycle problem has practical applications in various fields, such as logistics, network design, and computer science.
What is Hamiltonian Path?
Hamiltonian Path in a graph G is a path that visits every vertex of G exactly once and Hamiltonian Path doesn’t have to return to the starting vertex. It’s an open path.
- Similar to the Hamiltonian Cycle problem, finding a Hamiltonian Path in a general graph is also NP-complete and can be challenging. However, it is often a more easier problem than finding a Hamiltonian Cycle.
- Hamiltonian Paths have applications in various fields, such as finding optimal routes in transportation networks, circuit design, and graph theory research.
Problems Statement: Given an undirected graph, the task is to determine whether the graph contains a Hamiltonian cycle or not. If it contains, then prints the path.
Example:
Input: graph[][] = {{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}}

Input graph[][]
Output: {0, 1, 2, 4, 3, 0}.
Input: graph[][] = {{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}}

Input graph[][]
Output: Solution does not exist
Naive Algorithm: This problem can be solved using below idea:
Generate all possible configurations of vertices and print a configuration that satisfies the given constraints. There will be n! (n factorial) configurations. So the overall Time Complexity of this approach will be O(N!).
Create an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex 1. 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. If we do not find a vertex then we return false.
Illustrations:
Let’s find out the Hamiltonian cycle for the following graph:
.png)
- Start with the node 0 .
- Apply DFS for finding the Hamiltonian path.
- When base case reach (i.e. total no of node traversed == V (total vertex)):
- Check whether current node is a neighbour of starting node.
- As node 2 and node 0 are not neighbours of each other so return from it.

Starting from start node 0 calling DFS
- As cycle is not found in path {0, 3, 1, 4, 2}. So, return from node 2, node 4.

- Now, explore another option for node 1 (i.e node 2)
- When it hits the base condition again check for Hamiltonian cycle
- As node 4 is not the neighbour of node 0, again cycle is not found then return.

- Return from node 4, node 2, node 1.

- Now, explore other options for node 3.

Hamiltonian Cycle
- In the Hamiltonian path {0,3,4,2,1,0} we get cycle as node 1 is the neighbour of node 0.
- So print this cyclic path .
- This is our Hamiltonian cycle.
Below is the Backtracking implementation for finding Hamiltonian Cycle:
C++
/* C++ program for solution of Hamiltonian
Cycle problem using backtracking */
#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;
}
// This is code is contributed by rathbhupendra
C++
#include <iostream>
using namespace std;
int main() {
cout << "GFG!";
return 0;
}
C
/* C program for solution of Hamiltonian Cycle problem
using backtracking */
#include<stdio.h>
// 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[]') */
int isSafe(int v, int 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 0;
/* 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 0;
return 1;
}
/* A recursive utility function to solve hamiltonian cycle problem */
int hamCycleUtil(int 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 1;
else
return 0;
}
// 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) == 1)
return 1;
/* 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 0;
}
/* 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. */
int hamCycle(int graph[V][V])
{
int path[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) == 0 )
{
printf("\nSolution does not exist");
return 0;
}
printSolution(path);
return 1;
}
/* 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");
}
// driver program to test above function
int main()
{
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
int 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) */
int 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;
}
Java
/* Java program for solution of Hamiltonian Cycle problem
using backtracking */
class HamiltonianCycle
{
final int V = 5;
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[]') */
boolean isSafe(int v, int graph[][], 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 */
boolean hamCycleUtil(int graph[][], 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. */
int hamCycle(int graph[][])
{
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)
{
System.out.println("\nSolution does not exist");
return 0;
}
printSolution(path);
return 1;
}
/* A utility function to print solution */
void printSolution(int path[])
{
System.out.println("Solution Exists: Following" +
" is one Hamiltonian Cycle");
for (int i = 0; i < V; i++)
System.out.print(" " + path[i] + " ");
// Let us print the first vertex again to show the
// complete cycle
System.out.println(" " + path[0] + " ");
}
// driver program to test above function
public static void main(String args[])
{
HamiltonianCycle hamiltonian =
new HamiltonianCycle();
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
int graph1[][] = {{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
hamiltonian.hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
int graph2[][] = {{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
hamiltonian.hamCycle(graph2);
}
}
// This code is contributed by Abhishek Shankhadhar
Python
# Python program for solution of
# hamiltonian cycle problem
class Graph():
def __init__(self, vertices):
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
self.V = vertices
''' Check if this vertex is an adjacent vertex
of the previously added vertex and is not
included in the path earlier '''
def isSafe(self, v, pos, path):
# Check if current vertex and last vertex
# in path are adjacent
if self.graph[ path[pos-1] ][v] == 0:
return False
# Check if current vertex not already in path
for vertex in path:
if vertex == v:
return False
return True
# A recursive utility function to solve
# hamiltonian cycle problem
def hamCycleUtil(self, path, pos):
# base case: if all vertices are
# included in the path
if pos == self.V:
# Last vertex must be adjacent to the
# first vertex in path to make a cycle
if self.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 v in range(1,self.V):
if self.isSafe(v, pos, path) == True:
path[pos] = v
if self.hamCycleUtil(path, pos+1) == True:
return True
# Remove current vertex if it doesn't
# lead to a solution
path[pos] = -1
return False
def hamCycle(self):
path = [-1] * self.V
''' 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 self.hamCycleUtil(path,1) == False:
print ("Solution does not exist\n")
return False
self.printSolution(path)
return True
def printSolution(self, path):
print ("Solution Exists: Following",
"is one Hamiltonian Cycle")
for vertex in path:
print (vertex )
# Driver Code
''' Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) '''
g1 = Graph(5)
g1.graph = [ [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
g1.hamCycle();
''' Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) '''
g2 = Graph(5)
g2.graph = [ [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
g2.hamCycle();
# This code is contributed by Divyanshu Mehta
C#
// C# program for solution of Hamiltonian
// Cycle problem using backtracking
using System;
public class HamiltonianCycle
{
readonly int V = 5;
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, int [,]graph,
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(int [,]graph, 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. */
int hamCycle(int [,]graph)
{
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)
{
Console.WriteLine("\nSolution does not exist");
return 0;
}
printSolution(path);
return 1;
}
/* A utility function to print solution */
void printSolution(int []path)
{
Console.WriteLine("Solution Exists: Following" +
" is one Hamiltonian Cycle");
for (int i = 0; i < V; i++)
Console.Write(" " + path[i] + " ");
// Let us print the first vertex again
// to show the complete cycle
Console.WriteLine(" " + path[0] + " ");
}
// Driver code
public static void Main(String []args)
{
HamiltonianCycle hamiltonian =
new HamiltonianCycle();
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
int [,]graph1= {{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
hamiltonian.hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
int [,]graph2 = {{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
hamiltonian.hamCycle(graph2);
}
}
// This code contributed by Rajput-Ji
JavaScript
<script>
// JavaScript program for solution of Hamiltonian
// Cycle problem using backtracking
class HamiltonianCycle {
constructor() {
this.V = 5;
this.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[]') */
isSafe(v, graph, path, 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 (var i = 0; i < pos; i++) if (path[i] == v) return false;
return true;
}
/* A recursive utility function
to solve hamiltonian cycle problem */
hamCycleUtil(graph, path, pos) {
/* base case: If all vertices
are included in Hamiltonian Cycle */
if (pos == this.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 (var v = 1; v < this.V; v++) {
/* Check if this vertex can be
added to Hamiltonian Cycle */
if (this.isSafe(v, graph, path, pos)) {
path[pos] = v;
/* recur to construct rest of the path */
if (this.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. */
hamCycle(graph) {
this.path = new Array(this.V).fill(0);
for (var i = 0; i < this.V; i++) this.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 */
this.path[0] = 0;
if (this.hamCycleUtil(graph, this.path, 1) == false) {
document.write("<br>Solution does not exist");
return 0;
}
this.printSolution(this.path);
return 1;
}
/* A utility function to print solution */
printSolution(path) {
document.write(
"Solution Exists: Following" + " is one Hamiltonian Cycle <br>"
);
for (var i = 0; i < this.V; i++) document.write(" " + path[i] + " ");
// Let us print the first vertex again
// to show the complete cycle
document.write(" " + path[0] + " <br>");
}
}
// Driver code
var hamiltonian = new HamiltonianCycle();
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
var graph1 = [
[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
hamiltonian.hamCycle(graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
var graph2 = [
[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
hamiltonian.hamCycle(graph2);
// This code is contributed by rdtank.
</script>
PHP
<?php
// PHP program for solution of
// Hamiltonian Cycle problem
// using backtracking
$V = 5;
/* 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[]') */
function isSafe($v, $graph, &$path, $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 ($i = 0; $i < $pos; $i++)
if ($path[$i] == $v)
return false;
return true;
}
/* A recursive utility function
to solve hamiltonian cycle problem */
function hamCycleUtil($graph, &$path, $pos)
{
global $V;
/* 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 hamCycle()
for ($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. */
function hamCycle($graph)
{
global $V;
$path = array_fill(0, $V, 0);
for ($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)
{
echo("\nSolution does not exist");
return 0;
}
printSolution($path);
return 1;
}
/* A utility function to print solution */
function printSolution($path)
{
global $V;
echo("Solution Exists: Following is ".
"one Hamiltonian Cycle\n");
for ($i = 0; $i < $V; $i++)
echo(" ".$path[$i]." ");
// Let us print the first vertex again to show the
// complete cycle
echo(" ".$path[0]." \n");
}
// Driver Code
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3)-------(4) */
$graph1 = array(array(0, 1, 0, 1, 0),
array(1, 0, 1, 1, 1),
array(0, 1, 0, 0, 1),
array(1, 1, 0, 0, 1),
array(0, 1, 1, 1, 0),
);
// Print the solution
hamCycle($graph1);
/* Let us create the following graph
(0)--(1)--(2)
| / \ |
| / \ |
| / \ |
(3) (4) */
$graph2 = array(array(0, 1, 0, 1, 0),
array(1, 0, 1, 1, 1),
array(0, 1, 0, 0, 1),
array(1, 1, 0, 0, 0),
array(0, 1, 1, 0, 0));
// Print the solution
hamCycle($graph2);
// This code is contributed by mits
?>
OutputSolution 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.
Note: The above code always prints a cycle starting from 0. The starting point should not matter as the cycle can be started from any point. If you want to change the starting point, you should make two changes to the above code.
Change “path[0] = 0;” to “path[0] = s;” where s is your new starting point. Also change loop “for (int v = 1; v < V; v++)” in hamCycleUtil() to “for (int v = 0; v < V; v++)”.
Similar Reads
Hamiltonian Cycle
What is Hamiltonian Cycle?Hamiltonian Cycle or Circuit in a graph G is a cycle that visits every vertex of G exactly once and returns to the starting vertex. If graph contains a Hamiltonian cycle, it is called Hamiltonian graph otherwise it is non-Hamiltonian.Finding a Hamiltonian Cycle in a graph i
15+ min read
Number of Hamiltonian cycle
Given an undirected complete graph of N vertices where N > 2. The task is to find the number of different Hamiltonian cycle of the graph.Complete Graph: A graph is said to be complete if each possible vertices is connected through an Edge.Hamiltonian Cycle: It is a closed walk such that each vert
4 min read
Hamiltonian Path ( Using Dynamic Programming )
Given an adjacency matrix adj[][] of an undirected graph consisting of N vertices, the task is to find whether the graph contains a Hamiltonian Path or not. If found to be true, then print "Yes". Otherwise, print "No". A Hamiltonian path is defined as the path in a directed or undirected graph which
10 min read
Proof that Hamiltonian Cycle is NP-Complete
Prerequisite: NP-Completeness, Hamiltonian cycle. Hamiltonian Cycle: A cycle in an undirected graph G=(V, E) traverses every vertex exactly once. Problem Statement: Given a graph G=(V, E), the problem is to determine if graph G contains a Hamiltonian cycle consisting of all the vertices belonging to
4 min read
Print all Hamiltonian Cycles in an Undirected Graph
Given an undirected Graph consisting of N nodes in the form of an adjacency matrix graph[][] of size N*N, the task is to print all Hamiltonian cycles possible in the given undirected Graph (taking starting vertex as '0'). A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that t
15 min read
Proof that Hamiltonian Path is NP-Complete
A Hamiltonian Path in a graph is a path that visits each vertex exactly once. Given a graph G=(V,E)G = (V, E)G=(V,E), the Hamiltonian Path Problem (HPP) asks whether there exists such a path in GGG. If the path starts and ends at the same vertex, it is called a Hamiltonian Cycle. Step 1: Proving Ham
2 min read
Traveling Salesman Problem (TSP) Implementation
Given a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost. Note the differenc
8 min read
Permutation of numbers such that sum of two consecutive numbers is a perfect square
Prerequisite: Hamiltonian Cycle Given an integer n(>=2), find a permutation of numbers from 1 to n such that the sum of two consecutive numbers of that permutation is a perfect square. If that kind of permutation is not possible to print "No Solution". Examples: Input : 17 Output : [16, 9, 7, 2,
15+ min read