Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dijkstra's Algorithm and Cycles

It's stated in a book that "Dijkstra's algorithm only works with Directed Acyclic Graphs".

It appears the algorithm works for graphs with cycles too as long as there are no negative cycles. Is that correct?

Edit 1: The book "Grokking Algorithms" -Aditya Bhargava. Chapter 7. Page 122.

like image 563
sam Avatar asked Apr 13 '17 14:04

sam


People also ask

What is Dijkstra's algorithm used for?

Dijkstra's algorithm allows us to find the shortest path between any two vertices of a graph. It differs from the minimum spanning tree because the shortest distance between two vertices might not include all the vertices of the graph.

Is Dijkstra algorithm greedy?

Dijkstra Algorithm is a graph algorithm for finding the shortest path from a source node to all other nodes in a graph(single-source shortest path). It is a type of greedy algorithm. It only works on weighted graphs with positive weights.

Does Dijkstra work for negative weights without cycles?

Since Dijkstra's goal is to find the optimal path (not just any path), it, by definition, cannot work with negative weights, since it cannot find the optimal path.


2 Answers

I'm the author of Grokking Algorithms. Sorry for this error—Dijkstra's algorithm does work on graphs with cycles, as long as it is a positive weight cycle. I have updated the errata page to reflect this error. Dijkstra's doesn't work on negative weight cycles, and here's an image that explains why:

dijkstra's algorithm with a negative weight cycle

like image 84
Aditya Bhargava Avatar answered Sep 17 '22 15:09

Aditya Bhargava


Actually, it works as long as all edge weights are non-negative. This is a stronger condition as "no negative cycles". On the other hand it would not work on a DAG with negative weights. So, provided you cited correctly, the statement from the book is wrong for two reasons.

Btw. if you have negative cycles, there may no longer be a shortest path since you may cycle an infinite number of times and go down with your cost as much as you like.

like image 43
Henry Avatar answered Sep 16 '22 15:09

Henry