Algorithm for finding a Hamilton Path in a DAG

懵懂的女人 提交于 2019-11-29 22:52:03

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

I don't think the statement by @agassaa is entirely correct. Consider the simple example where there are three nodes "A", "B", "C", and edges A->B, B->C, A->C. While A has two children and C has two parents, A->B->C forms a Hamiltonian path. You don't need to traverse every edge in the graph for the path to be Hamiltonian.

A DAG that has Hamiltonian cycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!