I am referring to Skienna's Book on Algorithms.
The problem of testing whether a graph G
contains a Hamiltonian path
is NP-hard
, where a Hamiltonian path P
is a path that visits each vertex exactly once. There does not have to be an edge in G from the ending vertex to the starting vertex of P , unlike in the Hamiltonian cycle problem.
Given a directed acyclic graph G (DAG
), give an O(n + m)
time algorithm to test whether or not it contains a Hamiltonian path.
My approach,
I am planning to use DFS
and Topological sorting
. But I didn't know how to connect the two concepts in solving the problem. How can a topological sort be used to determine the solution.
Any suggestions?
P Find a Hamilton path in a DAG (if one exists). This can be found by computing the topological order and checking that there is an edge between each consecutive pair of vertices in the order.
1. Which of the following algorithm can be used to solve the Hamiltonian path problem efficiently? Explanation: The Hamiltonian path problem can be solved efficiently using branch and bound approach.
If a topological sort has the property that all pairs of consecutive vertices in the sorted order are connected by edges, then these edges form a directed Hamiltonian path in the DAG. If a Hamiltonian path exists, the topological sort order is unique; no other order respects the edges of the path.
Hamiltonian Path in an undirected graph is a path that visits each vertex exactly once. 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.
You can first topologically sort the DAG (every DAG can be topologically sorted) in O(n+m).
Once this is done, you know that edge go from lower index vertices to higher. This means that there exists a Hamiltonian path if and only if there are edge between consecutive vertices, e.g.
(1,2), (2,3), ..., (n-1,n).
(This is because in a Hamiltonian path you can't "go back" and yet you have to visit all, so the only way is to "not skip")
You can check this condition in O(n).
Thus, the overall complexity is O(m+n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With