Refactor distance calculation to hide graph