THE UNIVERSITY OF BIRMINGHAM
School of Computer Science
Software Workshop Java
Dijkstra's Algorithm

Mark Ryan


Dijkstra's algorithm

Dijkstra's algorithm finds the length of an optimal path between two vertices in a graph. (Optimal can mean shortest or cheapest or fastest or optimal in some other sense: it depends on how you choose to label the edges of the graph.) The algorithm works as follows:
  1. Choose the source vertex
  2. Define a set S of vertices, and initialise it to emptyset. As the algorithm progresses, the set S will store those vertices to which a shortest path has been found.
  3. Label the source vertex with 0, and insert it into S.
  4. Consider each vertex not in S connected by an edge from the newly inserted vertex. Label the vertex not in S with the label of the newly inserted vertex + the length of the edge.
  5. Pick a vertex not in S with the smallest label, and add it to S.
  6. Repeat from step 4, until the destination vertex is in S or there are no labelled vertices not in S.
If the destination is labelled, its label is the distance from source to destination. If it is not labelled, there is no path from the source to the destination.

Example

example

Suppose A is the source state. To explain the algorithm, we'll record the sequence of states we are in each time we get to step 4.
  1. A has label 0.  S = {A}.
  2. A has label 0, B has 14, D has 22, E has 4. S={A,E}.
  3. A is 0, B has label 14, D has been relabelled 16, F has 14. We inserted F (we could have chosen B instead). S={A,E,F}.
  4. No change to labels. S={A,E,F,B}
  5. Labels as before, and also G has 17. S={A,E,F,B,D}
  6. No change to labels. S={A,E,F,B,D,G}
  7. Stop because there are no labelled vertices not in S
The labels now record the shortest distance from A. (States with no label, such as C, cannot be reached from A.)

Dijkstra's algorithm calculates the length of the optimal path. But we can easily generalise it so that it can also give us the path itself. One way to do this is to maintain, along with the label for each node, the previous node we used to get there. Then the path can be extracted by starting at the destination and following the previous-node labels.

Programming the trains route finder

I suggest maintaining a tableau, perhaps stored as a hashmap, like in these examples. The label of a city is the earliest time we could reach that city. The tableau contains the cities we have labelled, and there is a boolean ("shortest?") which indicates whether that city is in S. The tableau also contains the previous node, to allow us to extract the shortest path, leg by leg, starting at the destination and working backwards.  See my examples.


Page written by Mark Ryan
Page maintained by Mark Ryan
Last modified: 29 October 2004