VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-hamiltonian-cycles-in-an-undirected-graph/

⇱ Print all Hamiltonian Cycles in an Undirected Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all Hamiltonian Cycles in an Undirected Graph

Last Updated : 23 Jul, 2025

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 there is an edge (in the graph) from the last vertex to the first vertex of the Hamiltonian Path.

Examples:

Input: graph[][] = {{0, 1, 1, 0, 0, 1}, {1, 0, 1, 0, 1, 1}, {1, 1, 0, 1, 0, 0}, {0, 0, 1, 0, 1, 0}, {0, 1, 0, 1, 0, 1}, {1, 1, 0, 0, 1, 0}}
Output: 
0 1 2 3 4 5 0 
0 1 5 4 3 2 0 
0 2 3 4 1 5 0 
0 2 3 4 5 1 0 
0 5 1 4 3 2 0 
0 5 4 3 2 1 0 
Explanation:
All Possible Hamiltonian Cycles for the following graph (with the starting vertex as 0) are 

👁 Image
  1. {0 ? 1 ? 2 ? 3 ? 4 ? 5 ? 0}
  2. {0 ? 1 ? 5 ? 4 ? 3 ? 2 ? 0}
  3. {0 ? 2 ? 3 ? 4 ? 1 ? 5 ? 0}
  4. {0 ? 2 ? 3 ? 4 ? 5 ? 1 ? 0}
  5. {0 ? 5 ? 1 ? 4 ? 3 ? 2 ? 0}
  6. {0 ? 5 ? 4 ? 3 ? 2 ? 1 ? 0}

Input: graph[][] = {{0, 1, 0, 1, 1, 0, 0}, {1, 0, 1, 0, 0, 0, 0}, {0, 1, 0, 1, 0, 0, 1}, {1, 0, 1, 0, 0, 1, 0}, {1, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 1, 1, 0, 1}, {0, 0, 1, 0, 0, 1, 0}}
Output: No Hamiltonian Cycle possible
Explanation:
For the given graph, no Hamiltonian Cycle is possible: 

👁 Image

Approach: The given problem can be solved by using Backtracking to generate all possible Hamiltonian Cycles. Follow the steps below to solve the problem:

  • Create an auxiliary array, say path[] to store the order of traversal of nodes and a boolean array visited[] to keep track of vertices included in the current path.
  • Initially, add the source vertex (in this case '0') to the path.
  • Now, recursively add vertices to path one by one to find the cycle.
  • Before adding a vertex to path, check whether the vertex being considered is adjacent to the previously added vertex or not and is not already in path. If such a vertex is found, then add it to the path and mark its value as true in the visited[] array.
  • If the length of path becomes equal to N, and there is an edge from the last vertex in path to 0, then print the path array.
  • After completing the above steps, if there exists no such path, then print No Hamiltonian Cycle possible.

Below is the implementation of the above approach:


Output: 
0 1 2 3 4 5 0 
0 1 5 4 3 2 0 
0 2 3 4 1 5 0 
0 2 3 4 5 1 0 
0 5 1 4 3 2 0 
0 5 4 3 2 1 0

 

Time Complexity: O(N!)
Auxiliary Space: O(N)

Comment