Finding the longest cycle in a directed graph using DFS

前端 未结 4 2039
夕颜
夕颜 2020-12-30 04:46

I need to find the longest cycle in a directed graph using DFS.

I once saw this Wikipedia article describing the way of doing this, and I think it approached the pro

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 05:17

    It can indeed be shown that you can reduce Hamiltonian cycle into this problem in polynomial time, so it ends up NP-complete. Regardless whether the graph is directed or undirected.

    As far as the algorithm, the easy way to solve the problem is to backtrack---start in nodes i=1 to n, and always explore all cycles starting in the particular node i. Once this is done, you eliminate the node i and continue for the rest of the graph, starting in node i+1. You may want to do something like node-coloring in DFS, to distinguish nodes that you never want to visit again and those that you visited along the path in this particular pass. You may also want to put something like a time-stamp on the nodes, similar to discovery times, but in this case you need to write these times everytime you discover a node, as most nodes will be discovered many times. The papers listed above could be helpful, and there are more ways to do this for sure.

提交回复
热议问题