next up previous contents index CD CD Algorithms
Next: All-Pairs Shortest Path Up: Shortest Paths Previous: Shortest Paths

Dijkstra's Algorithm

 

We can use Dijkstra's algorithm to find the shortest path between any two vertices (,t) in a weighted graph, where each edge has non-negative edge weight. Although most applications of shortest path involve graphs with positive edge weights, such a condition is not needed for either Prim's or Kruskal's algorithm to work correctly. The problems that negative edges cause Dijkstra's algorithm will become apparent once you understand the algorithm.  

The principle behind Dijkstra's algorithm is that given the shortest path between and each of a given set of vertices tex2html_wrap_inline25371 , there must exist some other vertex x such that the shortest path from to x must go from to tex2html_wrap_inline25373 to x, for some tex2html_wrap_inline25375 . Specifically, it is the vertex x that minimizes tex2html_wrap_inline25377 over all tex2html_wrap_inline25379 , where w(i,j) is the length of the edge from i to j and dist(i,j) is the length of the shortest path between them.

This suggests a dynamic programming-like strategy. The shortest path from to itself is trivial unless there are negative weight edges, so dist(,)=0. Armed with the shortest path to , if (,y) is the lightest edge incident to , then d(,y) = w(,y). As soon as we decide that we have determined the shortest path to a node x, we search through all the outgoing edges of x to see whether there is a better path from to some unknown vertex through x:


ShortestPath-Dijkstra(G,s,t)

tex2html_wrap_inline25391

for i=1 to n, tex2html_wrap_inline25395

for each edge (, v), dist[v]=w(, v)

last=

while ( tex2html_wrap_inline25403 )

select tex2html_wrap_inline25405 , the unknown vertex minimizing dist[v]

for each edge tex2html_wrap_inline25409 , tex2html_wrap_inline25411

tex2html_wrap_inline25413

tex2html_wrap_inline25415

To be certain of finding the shortest path between and t, we might have to first find the shortest path between and all other vertices. This defines a shortest path spanning tree rooted in . For undirected graphs, this will be the breadth-first search tree, but in general it provides the shortest path between and all other vertices.

What is the running time of this algorithm? When implemented using adjacency lists and a Boolean array to mark what is known about each vertex, the complexity is tex2html_wrap_inline25417 . This is the same running time as a proper version of Prim's algorithm; indeed, except for the extension condition, it is the same algorithm as Prim's.


next up previous contents index CD CD Algorithms
Next: All-Pairs Shortest Path Up: Shortest Paths Previous: Shortest Paths

Algorithms
Mon Jun 2 23:33:50 EDT 1997