public Route GetShortestRoute(RicePaddy start, RicePaddy end) { if (!m_shortestRoutesMap.ContainsKey(start)) { m_shortestRoutesMap[start] = CalculateShortestRoutes(start); } return(m_shortestRoutesMap[start][end]); }
// We will get the shortest path between the begin RicePaddy and the end RicePaddy by Dijkstra's algorithm. Dictionary <RicePaddy, Route> CalculateShortestRoutes(RicePaddy start) { var shortestRoutes = new Dictionary <RicePaddy, Route>(); var handled = new List <RicePaddy>(); foreach (var ricePaddy in m_ricePaddies) { shortestRoutes.Add(ricePaddy, new Route(ricePaddy.Identifier)); } shortestRoutes[start].TotalDistance = 0; while (handled.Count != m_ricePaddies.Count) { var shortestRicePaddies = shortestRoutes.OrderBy(_ => _.Value.TotalDistance).Select(_ => _.Key).ToArray(); var processing = default(RicePaddy); foreach (var ricePaddy in shortestRicePaddies) { if (!handled.Contains(ricePaddy)) { if (shortestRoutes[ricePaddy].TotalDistance == int.MaxValue) { return(shortestRoutes); } processing = ricePaddy; break; } } var selectedRoads = m_roads.Where(_ => _.A == processing); foreach (var road in selectedRoads) { if (shortestRoutes[road.B].TotalDistance > road.Distance + shortestRoutes[road.A].TotalDistance) { var roads = shortestRoutes[road.A].Roads.ToList(); roads.Add(road); shortestRoutes[road.B].Roads = roads; shortestRoutes[road.B].TotalDistance = road.Distance + shortestRoutes[road.A].TotalDistance; } } handled.Add(processing); } return(shortestRoutes); }
// We will get the shortest path between the begin RicePaddy and the end RicePaddy by Dijkstra's algorithm. Dictionary<RicePaddy, Route> CalculateShortestRoutes(RicePaddy start) { var shortestRoutes = new Dictionary<RicePaddy, Route>(); var handled = new List<RicePaddy>(); foreach (var ricePaddy in m_ricePaddies) { shortestRoutes.Add(ricePaddy, new Route(ricePaddy.Identifier)); } shortestRoutes[start].TotalDistance = 0; while (handled.Count != m_ricePaddies.Count) { var shortestRicePaddies = shortestRoutes.OrderBy(_ => _.Value.TotalDistance).Select(_ => _.Key).ToArray(); var processing = default(RicePaddy); foreach (var ricePaddy in shortestRicePaddies) { if (!handled.Contains(ricePaddy)) { if (shortestRoutes[ricePaddy].TotalDistance == int.MaxValue) return shortestRoutes; processing = ricePaddy; break; } } var selectedRoads = m_roads.Where(_ => _.A == processing); foreach (var road in selectedRoads) { if (shortestRoutes[road.B].TotalDistance > road.Distance + shortestRoutes[road.A].TotalDistance) { var roads = shortestRoutes[road.A].Roads.ToList(); roads.Add(road); shortestRoutes[road.B].Roads = roads; shortestRoutes[road.B].TotalDistance = road.Distance + shortestRoutes[road.A].TotalDistance; } } handled.Add(processing); } return shortestRoutes; }
public Route GetShortestRoute(RicePaddy start, RicePaddy end) { if (!m_shortestRoutesMap.ContainsKey(start)) m_shortestRoutesMap[start] = CalculateShortestRoutes(start); return m_shortestRoutesMap[start][end]; }