![]() |
VOOZH | about |
Given a directed graph of N vertices valued from 0 to N - 1 and array graph[] of size K represents the Adjacency List of the given graph, the task is to count all Hamiltonian Paths in it which start at the 0th vertex and end at the (N - 1)th vertex.
Note: Hamiltonian path is defined as the path which visits every vertex of the graph exactly once.
Examples:
Input: N = 4, K = 6, graph[][] = {{1, 2}, {1, 3}, {2, 3}, {3, 2}, {2, 4}, {3, 4}}
Output: 2
Explanation:
The paths below shown are 1 -> 3 -> 2 -> 4 and 1 -> 2 -> 3 -> 4 starts at 1 and ends at 4 and are called Hamiltonian paths.Input: N = 2, K = 1, graph[][] = {{1, 2}}
Output: 1
Approach: The given problem can be solved by using Bitmasking with Dynamic Programming, and iterate over all subsets of the given vertices represented by an N size mask and check if there exists a Hamiltonian Path that starts at the 0th vertex and ends at (N - 1)th vertex and count all such paths. Let's say for a graph having N vertices S represents a bitmask where S = 0 to S = (1 << N) -1 and dp[i][S] represents the number of paths that visits every vertex in the mask S and ends at i then the valid recurrence will be given as dp[i][S] = ∑ dp[j][S XOR 2i] where j ∈ S and there is an edge from j to i where S XOR 2i represents the subset which does not have the ith vertex in it and there must be an edge from j to i. Follow the steps below to solve the given problem:
Below is the implementation of the above approach:
2
Time Complexity: O(N*2N)
Auxiliary Space: O(1)