Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dijkstra for longest path in a DAG

I am trying to find out if it is possible to use Dijkstra's algorithm to find the longest path in a directed acyclic path. I know that it is not possible to find the longest path with Dijkstra in a general graph, because of negative cost cycles. But it should work in a DAG, I think. Through Google I found a lot of conflicting sources. Some say it works in a dag and some say it does not work, but I didn't find a proof or a counter example. Can someone point me to a proof or a counter example?

like image 401
punkyduck Avatar asked Nov 06 '11 13:11

punkyduck


People also ask

Can you use Dijkstra for longest path?

I found two special cases where you can use Dijkstra for calculating the longest path: The graph is not only directed acyclic, but also acyclic if you remove the directions. In other words: It is a tree. Because in a tree the longest path is also the shortest path.

How do I find the longest path in DAG?

The recursive formula will be: dp[node] = max(dp[node], 1 + max(dp[child1], dp[child2], dp[child3]..)) At the end check for the maximum value in dp[] array, which will be the longest path in the DAG.

Does Dijkstra work for DAG?

Show activity on this post. I think Dijkstra's algorithm will work for DAG if there is no negative weight. Because Dijkstra's algorithm can't give the right answer for negative weighted edges graph. But sometimes it does based on graph type.

Can Dijkstra's algorithm be used to find the single source longest path in A DAG G v e given all weights are positive?

Yes, I think it can be modified.


1 Answers

I thought about the problem and I think it is not possible in general. Being acyclic is not enough, I think.

For example:

We want to go from a to c in this dag.

a - > b - > c
|           /\
v           |
d - - - - - 

d-c has length 4

a-d has length 1

all others have length 2

If you just replace the min function with a max function, the algorithm will lead to a-b-c but the longest path is a-d-c.

I found two special cases where you can use Dijkstra for calculating the longest path:

  1. The graph is not only directed acyclic, but also acyclic if you remove the directions. In other words: It is a tree. Because in a tree the longest path is also the shortest path.
  2. The graph has only negative weights. Then you can use max instead of min to find the longest path. BUT this works only if the weights are really negative. If you just invert positive weights it will not work.
like image 92
punkyduck Avatar answered Oct 22 '22 14:10

punkyduck