// 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
. 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
,
and be faster if one uses the adjacency list representation.