Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dijkstra's algorithm on directed acyclic graph with negative edges

Will Dijkstra's algorithm work on a graph with negative edges if it is acyclic (DAG)? I think it would because since there are no cycles there cannot be a negative loop. Is there any other reason why this algorithm would fail?

Thanks [midterm tomorrow]

like image 204
Marcus Avatar asked Mar 11 '15 20:03

Marcus


People also ask

Does Dijkstra algorithm work for negative edges?

Dijkstra's algorithm solves the shortest-path problem for any weighted, directed graph with non-negative weights. It can handle graphs consisting of cycles, but negative weights will cause this algorithm to produce incorrect results.

Can Dijkstra handle negative weights in acyclic graph?

No, it cannot be used when there are negative weights. The reason is that it is a greedy algorithm.

Does Dijkstra's algorithm ever work when some of the edge costs are negative?

In conclusion, Dijkstra's algorithm never ends if the graph contains at least one negative cycle. By a negative cycle, we mean a cycle that has a negative total weight for its edges.

Why does Dijkstra's algorithm need the edges of the graph to be non negative?

It happens because, in each iteration, the algorithm only updates the answer for the nodes in the queue. So, Dijkstra's algorithm does not reconsider a node once it marks it as visited even if a shorter path exists than the previous one. Hence, Dijkstra's algorithm fails in graphs with negative edge weights.


1 Answers

Consider the graph (directed 1 -> 2, 2-> 4, 4 -> 3, 1 -> 3, 3 -> 5):

  1---(2)---3--(2)--5
  |         |
 (3)      (2)
  |         |  
  2--(-10)--4

The minimum path is 1 - 2 - 4 - 3 - 5, with cost -3. However, Dijkstra will set d[3] = 2, d[2] = 3 in the first step, then extract node 3 from its priority queue and set d[5] = 4. Since node 3 was extracted from the priority queue, and Dijkstra does not push a given node to its priority queue more than once, it will never end up in it again, so the algorithm won't work.

Dijkstra's algorithm does not work with negative edges, period. The absence of a cycle changes nothing. Bellman-Ford is the one that can detect negative cost cycles and works with negative edges. Dijkstra will not work if you can have negative edges.

If you change Dijkstra's algorithm such that it can push a node to the priority queue more than once, then the algorithm will work with negative cost edges. But it is debatable if the new algorithm is still Dijkstra's: I would say you get Bellman-Ford that way, which is often implemented exactly like that (well, usually a FIFO queue is used and not a priority queue).

like image 162
IVlad Avatar answered Sep 30 '22 15:09

IVlad