VOOZH about

URL: https://www.geeksforgeeks.org/dsa/hamiltonian-path-using-dynamic-programming/

⇱ Hamiltonian Path ( Using Dynamic Programming ) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Hamiltonian Path ( Using Dynamic Programming )

Last Updated : 23 Jul, 2025

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 visits each and every vertex of the graph exactly once.

Examples:

Input: adj[][] = {{0, 1, 1, 1, 0}, {1, 0, 1, 0, 1}, {1, 1, 0, 1, 1}, {1, 0, 1, 0, 0}}
Output: Yes
Explanation:
There exists a Hamiltonian Path for the given graph as shown in the image below:

👁 Image

Input: adj[][] = {{0, 1, 0, 0}, {1, 0, 1, 1}, {0, 1, 0, 0}, {0, 1, 0, 0}}
Output: No

Naive Approach: The simplest approach to solve the given problem is to generate all the possible permutations of N vertices. For each permutation, check if it is a valid Hamiltonian path by checking if there is an edge between adjacent vertices or not. If found to be true, then print "Yes". Otherwise, print "No".

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

Efficient Approach: The above approach can be optimized by using Dynamic Programming and Bit Masking which is based on the following observations:

  • The idea is such that for every subset S of vertices, check whether there is a hamiltonian path in the subset S that ends at vertex v where v € S.
  • If v has a neighbor u, where u € S - {v}, therefore, there exists a Hamiltonian path that ends at vertex u.
  • The problem can be solved by generalizing the subset of vertices and the ending vertex of the Hamiltonian path.

Follow the steps below to solve the problem:

  • Initialize a boolean matrix dp[][] in dimension N*2N where dp[j ][i] represents whether there exists a path in the subset or not represented by the mask i that visits each and every vertex in i once and ends at vertex j.
  • For the base case, update dp[i][1 << i] = true, for i in range [0, N - 1]
  • Iterate over the range [1, 2N - 1] using the variable i and perform the following steps:
    • All the vertices with bits set in mask i, are included in the subset.
    • Iterate over the range [1, N] using the variable j that will represent the end vertex of the hamiltonian path of current subset mask i and perform the following steps:
  • Iterate over the range using the variable i and if the value of dp[i][2N - 1] is true, then there exists a hamiltonian path ending at vertex i. Therefore, print "Yes". Otherwise, print "No".

Below is the implementation of the above approach:


Output: 
YES

 

Time Complexity: O(N2 * 2N)
Auxiliary Space: O(N * 2N)

Comment
Article Tags:
Article Tags: