Dijkstra's Algorithm
Notes
- Given a graph with positive weights, and a source and a destination, find the lowest cost path from the source to the destination.
- Your GPS probably loves Dijkstra.
- But also probably A* and heuristics
- As does your router
- Dijkstra finds the shortest path from the source to every other node, which includes the destination.
- The algorithm can be O(V + E log2V)
- It is the best general shortest path algorithm we know, but in special cases we can build faster ones.
- Dijkstra claims to have invented the algorithm in 20 minutes
What is the shortest way to travel from Rotterdam to Groningen, in general: from given city to given city. It is the algorithm for the shortest path, which I designed in about twenty minutes. One morning I was shopping in Amsterdam with my young fiancee, and tired, we sat down on the cafe terrace to drink a cup of coffee and I was just thinking about whether I could do this, and I then designed the algorithm for the shortest path. As I said, it was a twenty-minute invention. In fact, it was published in '59, three years later. The publication is still readable, it is, in fact, quite nice. One of the reasons that it is so nice was that I designed it without pencil and paper. I learned later that one of the advantages of designing without pencil and paper is that you are almost forced to avoid all avoidable complexities. Eventually, that algorithm became to my great amazement, one of the cornerstones of my fame.
Edsger Dijkstra, in an interview with Philip L. Frana, Communications of the ACM, 2001
-
DIKJSTRA(G, s)
- for each vertex v ∈ G.V
- v.d = ∞
- v.π = NIL
- Q.enqueue(v)
- source.d = 0
- while not Q.empty() do
- u = Q.ExtractMin()
- for each v ∈ G.Adj(u)
- if u.d + w(u,v) < v.d
- v.d = u.d + w(u,v)
- v.π = u
- Lines 1-4 are called INITIALIZE-SINGLE-SOURCE in CLRS
- Lines 9-11 are called RELAX in CLRS
- They reuse these in other algorithms.