private string GetMinPath() { var result = new StringBuilder(); long currentIndex = _toCity; while (currentIndex != _fromCity) { DistancePath path = _distancePathByCityNumber[currentIndex]; result.Insert(0, $" {currentIndex + 1}"); currentIndex = path.BackCity; } result.Insert(0, (_fromCity + 1).ToString()); return(result.ToString()); }
public MinDistanceResult GetMinDistance() { if (_result != null) { return(_result); } _heap.Add(new CityDistance(_fromCity, _fromCity, 0)); while (!_minDistanceCities.Contains(_toCity)) { CityDistance currentCity = _heap.Pop(); long currentCityIndex = currentCity.To; if (currentCity == null) { return(MinDistanceResult.NotFound()); } _minDistanceCities.Add(currentCityIndex); var roadsFromCurrentCity = _distanceMap.GetRoadsFromCity(currentCityIndex); foreach (var(toCity, distance) in roadsFromCurrentCity) { long newDistance = distance + currentCity.Distance; long currentMinDistance = _distancePathByCityNumber.ContainsKey(toCity) ? _distancePathByCityNumber[toCity].Distance : long.MaxValue; if (newDistance < currentMinDistance) { _heap.Add(new CityDistance(currentCityIndex, toCity, newDistance)); _distancePathByCityNumber[toCity] = new DistancePath(newDistance, currentCityIndex); } } } _result = new MinDistanceResult( _distancePathByCityNumber[_toCity].Distance, GetMinPath()); return(_result); }