![]() |
VOOZH | about |
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: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:
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
YES
Time Complexity: O(N2 * 2N)
Auxiliary Space: O(N * 2N)