calculating distances with intermediary vertices