Longest path in a DAG

≯℡__Kan透↙ 提交于 2019-11-27 03:22:28

问题


To find the longest path in a DAG, I'm aware of 2 algorithms: algo 1: do a topological sort + use dynamic programming on the result of the sort ~ or ~ algo 2: enumerate all the paths in the DAG using DFS, and record the longest. It seems like enumerating all the paths with DFS has better complexity than algo 1. Is that true?


回答1:


Your second option is incorrect: DFS does not explore all possible paths, unless your graph is a tree or a forest, and you start from the roots. The second algorithm that I know is negating the weights and finding the shortest path, but it is somewhat slower than the top sort + DP algorithm that you listed as #1.




回答2:


Enumerate all paths in a DAG using "DFS":

def enumerate_dag(g):

  def enumerate_r(n, paths, visited, a_path = []):
    a_path += [n]
    visited[n] = 1
    if not g[n]:
        paths += [list(a_path)]
    else:
        for nn in g[n]:
            enumerate_r(nn, paths, visited, list(a_path))

  paths, N = [], len(g)
  visited = np.zeros((N), dtype='int32')

  for root in range(N):
    if visited[root]: continue
    enumerate_r(root, paths, visited, [])

  return paths



回答3:


No DFS needed. Algorithm : takes a DAG G. Each arc holds one variable E

for each node with no predecessor :
    for each of his leaving arcs, E=1.
for each node whose predecessors have all been visited :
    for each of his leaving arcs, E=max(E(entering arcs))+1.

max_path is the highest E within edges when all nodes have been processed.



来源:https://stackoverflow.com/questions/10712495/longest-path-in-a-dag

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