VOOZH about

URL: https://www.geeksforgeeks.org/dsa/hamiltonian-cycle/

⇱ Hamiltonian Cycle - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Hamiltonian Cycle

Last Updated : 31 Jan, 2026

A Hamiltonian Cycle or Circuit in a graph G is a cycle that visits each vertex of G exactly once and returns to the starting vertex.

  • If a graph has a Hamiltonian cycle, it's a Hamiltonian graph; otherwise, it's non-Hamiltonian.
  • Finding a Hamiltonian cycle is an NP-complete problem, meaning there's no known efficient solution for all graph types, but solutions exist for smaller or specific types.
  • The Hamiltonian Cycle problem has applications in logistics, network design, and computer science.

Sample Problem

Given an undirected graph, the task is to determine if it contains a Hamiltonian cycle. If found, print the path; otherwise, print "Solution does not exist".

Examples:

Input: N=5, adjMat[][] = [[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]]

👁 409843078

Output: [0, 1, 2, 4, 3, 0]

Input: N=5, adjMat[][] = [[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]]

👁 420851416

Output: "Solution Does Not Exists"

[Naive Approach] Generate All Configurations

Generate all possible vertex configurations and print a configuration that satisfies the given constraints. This results in n! (n factorial) configurations. Therefore, the overall time complexity of this approach is at least O(n!).

[Expected Approach] Using Backtracking

Backtracking is used to find a Hamiltonian Cycle. Initialize an empty path array, place the starting vertex (e.g., 0) in the first position. Recursively add remaining vertices one by one, ensuring each new vertex is adjacent to the previous one and not already in the path. If a valid vertex is found, proceed; otherwise, backtrack.

Exemplification

Let's find out the Hamiltonian cycle for the following graph:

👁 409843078
  • Start with node 0. Apply DFS to find a Hamiltonian path.
  • When all 'n' vertices are traversed, check if the current node is a neighbor of the starting node.
  • Since node 2 is not a neighbor of 0, return. As no cycle is found in path {0, 3, 1, 4, 2}, return from nodes 2 and 4.
👁 3
  • Explore node 2. Check for a Hamiltonian cycle. Since node 4 is not a neighbor of 0, return. Return from nodes 4, 2, and 1.
👁 1-1
  • Explore node 3. In path {0, 3, 4, 2, 1, 0}, a cycle is found, print this cyclic path. This is our Hamiltonian cycle.
👁 4

Note: The algorithm currently starts from a fixed vertex, but a Hamiltonian cycle allows any vertex. Minor adjustments are needed to enable cycle initiation from any node.


Output
0 1 2 4 3 0

Time Complexity: O(n!)
Space Complexity: O(n)

Comment
Article Tags: