31

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?

ks1322
  • 29,461
  • 12
  • 91
  • 140
user2302617
  • 349
  • 1
  • 3
  • 7

1 Answers1

54

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).

Petar Ivanov
  • 84,604
  • 7
  • 74
  • 90
  • But you assumed the graph is connected, can't there be a topological sort for a graph that has disconnected parts? – shinzou Mar 14 '16 at 20:55
  • 3
    I do NOT assume that the graph is connected.If the graph is not connected then there is no Hamiltonian and this algorithm will detect it, because at least one of the consecutive vertices won't be connected (or else the graph will be connected). – Petar Ivanov Mar 18 '16 at 19:03
  • 1
    What about Hamiltonian cycles, euler path and euler cycles in the same time? – Kiran Baktha Nov 15 '17 at 17:31