Algorithm for distance added.