4

Is there is an algo/efficient way to calculate the distance from each vertex in a graph to all other vertices.

Unlike Dijkstra - I'm looking for a way to calculate a distance for all vertices to all vertices (not one to all).

Thanks!

Vitali Melamud
  • 1,267
  • 17
  • 40

1 Answers1

6

If by "distance" you mean "shortest distance", then the answer is "Yes". A very popular algorithm for all-pairs shortest paths is Floyd Warshall Algorithm. It is remarkably easy to implement:

for k = 0 ; k != N ; k++
    for i = 0 ; i != N ; i++
        for j = 0 ; j != N ; j++
            W[i,j] = MIN(W[i,j], W[i,k]+W[k,j])

It wouldn't work for large-scale sparse graphs, however, because it uses an adjacency matrix implementation. It also does not work with graphs that have negative cycles, because shortest paths in such graphs are undefined.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    @VitaliMelamud There's [Johnson's algorithm](http://en.wikipedia.org/wiki/Johnson%27s_algorithm), which has better space efficiency for sparse graphs. – Sergey Kalinichenko Feb 01 '15 at 10:09
  • Basically Johnson's algorithm is running Dijkstra on every vertex. Is there a way to make this better? That is - use the data from every Dijkstra iteration to shorten the next ones? – Vitali Melamud Feb 01 '15 at 10:17
  • @VitaliMelamud Not in a general case. I remember researching this extensively for a project, but I couldn't find anything that would be better on a graph without additional special properties. – Sergey Kalinichenko Feb 01 '15 at 10:29