- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace BLL
- {
- public class PathFinder
- {
- Dictionary<BatteryCenter, double> listDistance = new Dictionary<BatteryCenter, double>();
- Dictionary<BatteryCenter, BatteryCenter> listPrevious = new Dictionary<BatteryCenter, BatteryCenter>();
- public List<BatteryCenterDistance> FindPathFromCityToCity(Map map, BatteryCenter from, BatteryCenter to, double range)
- {
- using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\log\map.txt", true))
- {
- file.WriteLine("COUNT: {0} - RANGE {1}", map.Stations.Count, range);
- file.WriteLine("FROM: {0} - TO: {1}", from.name, to.name);
- foreach (var m in map.Stations)
- {
- file.WriteLine("C: {0} - E: {1} - T: {2}", m.name, m.Edgelist.Count, m.GetType());
- }
- }
- List<BatteryCenterDistance> list = new List<BatteryCenterDistance>();
- if (map.IsAdjacent(from, to))
- {
- list.Add(new BatteryCenterDistance() { BatteryCenter = from, Distance = 0 });
- list.Add(new BatteryCenterDistance() { BatteryCenter = to, Distance = map.FindEdge(from, to).distance });
- }
- else
- {
- CalculateDistance(map, from, range);
- while (listPrevious[to] != null)
- {
- var b = map.FindEdge(to, listPrevious[to]);
- list.Add(new BatteryCenterDistance() { BatteryCenter = to, Distance = (b != null ? b.distance : 0) });
- to = listPrevious[to];
- }
- list.Add(new BatteryCenterDistance() { BatteryCenter = from, Distance = 0 });
- list.Reverse();
- double covered = 0.0;
- BatteryCenterDistance bcd = new BatteryCenterDistance();
- foreach (var b in list)
- {
- if ((covered + b.Distance >= range))
- {
- if (b.Distance > range)
- b.Possible = false;
- else
- {
- bcd.Stop = true;
- covered = b.Distance;
- }
- }
- else
- covered += b.Distance;
- bcd = b;
- }
- }
- return list;
- }
- private void CalculateDistance(Map map, BatteryCenter from, double range)
- {
- List<BatteryCenter> listTemp = new List<BatteryCenter>();
- foreach (BatteryCenter b in map.Stations)
- {
- listDistance[b] = Double.PositiveInfinity;
- listPrevious[b] = null;
- b.Mark = false;
- }
- listDistance[from] = 0;
- listTemp.Add(from);
- while (listTemp.Count > 0)
- {
- BatteryCenter current = null;
- double distance = Double.PositiveInfinity;
- foreach (BatteryCenter v in listTemp)
- {
- if (listDistance[v] < distance)
- {
- current = v;
- distance = listDistance[v];
- }
- }
- listTemp.Remove(current);
- current.Mark = true;
- foreach (var _edge in current.Edgelist)
- {
- BatteryCenter b = map.Stations.FirstOrDefault(x => x.name.Equals(_edge.BatteryStation1.name));
- if (((listDistance[current] + _edge.distance) < listDistance[b]) && !b.Mark && (_edge.distance <= range))
- {
- listDistance[b] = listDistance[current] + _edge.distance;
- listPrevious[b] = current;
- listTemp.Add(b);
- }
- }
- }
- }
- }
- }