updating distances when necessary