next up previous contents
Next: Minimal spanning trees Up: Graphs Previous: Dijkstra's algorithm, version II.   Contents

Shortest path for all vertices.

If we are not just interested in finding the shortest path from one specific vertex to all others, but between every pair of vertices we could, of course, apply Dijkstra's algorithm to every starting vertex. But there is a simpler way of doing this. We keep a matrix `distance' which contains overestimates of the lengths for every pair of vertices. We decrease overestimates using the same idea as above. In the algorithm given below, we attempt to decrease the estimate of the distance from a vertex $ s$ to a vertex $ z$ by going systematically via each possible vertex $ u$ to see whether there is a shortcut; if there is, the overestimate of the distance is decreased to a smaller overestimate.

   // Store initial estimates.

   for (each vertex s)
       for (each vertex z)
           distance[s][z] = weight[s][z];

   // Improve them until they are tight.
   for (each vertex s)
       for (each vertex z)
           for (each vertex u)
                if (distance[s][u]+distance[u][z] < distance[s][z])
                   distance[s][z] = distance[s][u]+distance[u][z];
If we wish to also keep track of which the shortest path is, rather than just its length, we need to introduce a second matrix keeping track of the `previous vertex' (exercise).

This is known as Floyd's algorithm. Its complexity class is quite obviously $ O(n^{3})$. Again it can be adapted to non-weighted graphs by choosing a suitable weight matrix. In general, Floyd's algorithm will be faster than Dijkstra's, although both are in the same complexity class. This is due to the fact that the former performs fewer instructions in each run through the loops. If the number of edges is small against the number of vertices, however, then, Dijkstra's algorithm can be made to perform in $ O(nm +\log n)$, and be faster if one uses the adjacency list representation.


next up previous contents
Next: Minimal spanning trees Up: Graphs Previous: Dijkstra's algorithm, version II.   Contents
Martin Escardo 2005-01-11