public RouteNode(string airport, Flight flight, RouteNode prevNode) { this.prevNode = prevNode; this.flight = flight; Airport = airport; Depth = prevNode == null ? 0 : prevNode.Depth + 1; }
public async Task <Flight[]> FindRouteAsync(string srcAirport, string destAirport, CancellationToken ct) { var visitedAirports = new HashSet <string> { srcAirport }; var queue = new Queue <RouteNode>(); queue.Enqueue(new RouteNode(srcAirport, null, null)); while (!ct.IsCancellationRequested && queue.Count > 0) { List <RouteNode> parents = BatchDequeue(queue, config.MaxDegreeOfParallelism); List <Flight>[] childrenData = await Task.WhenAll( parents.Select(item => flightsService.GetActiveOutgoingFlightsAsync(item.Airport)) ); if (ct.IsCancellationRequested) { break; } for (int i = 0; i < childrenData.Length; i++) { RouteNode parent = parents[i]; List <Flight> outgoingFlights = childrenData[i]; foreach (var flight in outgoingFlights) { if (flight.DestAirport == destAirport) { return(new RouteNode(flight.DestAirport, flight, parent).GetFullRoute()); } if (visitedAirports.Contains(flight.DestAirport)) { continue; } visitedAirports.Add(flight.DestAirport); if (parent.Depth + 1 < config.MaxRouteDepth) { queue.Enqueue(new RouteNode(flight.DestAirport, flight, parent)); } } } } if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } return(Array.Empty <Flight>()); }
public Flight[] GetFullRoute() { if (Depth == 0) { return(Array.Empty <Flight>()); } Flight[] result = new Flight[Depth]; RouteNode node = this; for (int i = Depth; i > 0; i--) { result[i - 1] = node.flight; node = node.prevNode; } return(result); }