Algorithm to calculate shortest path distances.