How to find the longest simple path in a graph?

丶灬走出姿态 提交于 2019-12-01 05:49:20

问题


I know that for non-directed graph this problem is NP-complete hence we should do Brute Force in order to check all possible paths. How we can do that? Please suggest a pseudo code and tell me the complexity of that algorithm.

If there are optimizations, then that would be awesome!


回答1:


A naïvem approach could run through all possible vertex permutations.

For every permutation {v1, ..., vN} you check if you can get from v1 to v2, then from v2 to v3 etc. If you can, add corresponding edge length to the current path length. If not, go to the next permutation.

The longest of such paths is your answer.


Or, you could do pretty much the same using recursion.

path = 0
bestPath = 0
used = new bool[N] // initialize with falses
for(u = 0; u < N; u++)
    Path(u); // build paths starting from u
print bestPath

where

Path(u)
    used[u] = true
    foreach v in neighborhood(u)
        if(!used[v])
            path += distance(u, v)
            bestPath = max(bestPath, path)
            Path(v)
            path -= distance(u, v)
    used[u] = false

Time complexity is horrible O(N * N^N).




回答2:


If your graph is a special case in which it's directed and acyclic, you could do a dynamic programming approach such as the one described here. You basically sort your graph topologically, then in the topological order, for every node V, you check all its neighbors and update their "distance" value if it's bigger than the "distance" already memorized (initialized with -infinity or something).

Otherwise, in the general case, the problem is indeed NP-complete as it reduces to the Hamiltonian cycle. One thing you could do is negate all the edges and try the Bellman-Ford Algorithm. Beware that it's not good for negative cycles, however.



来源:https://stackoverflow.com/questions/21880419/how-to-find-the-longest-simple-path-in-a-graph

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