Problem Description
Given a graph of n cities and a list of flights—each represented as [from, to, price]—find the cheapest flight route from a source city (src) to a destination city (dst) with at most k stops. If no such route exists, return -1.
Key Insights
- Use a variant of BFS combined with a min-heap (priority queue) to always expand the cheapest route.
- Each state in the queue includes the current cost, current city, and the number of stops used so far.
- Track the best-known cost to reach a city with a certain number of stops to prune non-optimal routes.
- Ensure that you do not exceed k stops during exploration.
Space and Time Complexity
Time Complexity: O(E log(E)) in the worst-case scenario, where E is the number of flights, due to the heap operations. Space Complexity: O(n + E) for storing the graph and auxiliary data structures like the heap and best-cost map.
Solution
We solve the problem using a modified Dijkstra's algorithm. The approach employs a min-heap to ensure that we always process the state with the lowest cumulative cost next. Each state tracks the total cost so far, the current city, and the number of stops made. When a state reaches the destination city, we return its cost. To avoid unnecessary work, we record the lowest cost at which each city has been reached with a given number of stops. This state-tracking helps prune routes that are more expensive or exceed the allowed number of stops.