public static List<Flight> FindFastestRoute(List<Flight> flights, string from, string to) { var mapFligth = new MapFlight(); flights.ForEach(f => { mapFligth.AddConnection(f.FromAirportCode, f); }); var routesFromOrigin = new List<List<Flight>>(); if (mapFligth.connections.ContainsKey(from)) { mapFligth.connections[from].ForEach(x => { var alreadyFlew = new List<string>(); var flightsToTake = new List<Flight>(); alreadyFlew.Add(from); routesFromOrigin.Add(possibleRoute(mapFligth, alreadyFlew, flightsToTake, x, to)); }); } var routesUntilDestination = new List<List<Flight>>(); foreach (var route in routesFromOrigin.Where(rs => rs.Any(f => f.ToAirportCode == to))) { routesUntilDestination.Add(route.GetRange(0, route.IndexOf(route.First(f => f.ToAirportCode == to)) + 1)); } return routesUntilDestination.OrderBy(c => c.Count).FirstOrDefault() ?? new List<Flight>(); }
private static List<Flight> possibleRoute(MapFlight map, List<string> alreadyFlew, List<Flight> take, Flight connection, string to) { alreadyFlew.Add(connection.ToAirportCode); take.Add(connection); if (connection.ToAirportCode == to) { return take; } else { if (map.connections.ContainsKey(connection.ToAirportCode)) { map.connections[connection.ToAirportCode].ForEach(c => { if (!alreadyFlew.Contains(c.ToAirportCode)) { possibleRoute(map, alreadyFlew, take, c, to); } }); } } return take; }