Imagine you're a travel agent trying to find the most budget-friendly flight route for your client. You have access to a network of n cities connected by various flights, where each flight has a specific cost.
You're given an array flights where flights[i] = [from_i, to_i, price_i] represents a direct flight from city from_i to city to_i costing price_i dollars. Your client wants to travel from a source city src to a destination city dst, but here's the catch: they can make at most k stops along the way.
Your mission: Find the cheapest possible price for this journey. If no valid route exists within the stop limit, return -1.
Example: If there are flights [0,1,100], [1,2,100], [0,2,500] and you want to go from city 0 to city 2 with at most 1 stop, you should choose the route 0→1→2 (cost: 200) instead of the direct flight 0→2 (cost: 500).
Input & Output
Time & Space Complexity
We iterate k+1 times, and for each iteration process all E flights
DP table stores costs for each (stops, city) combination
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ flights.length ≤ n * (n - 1) / 2
- flights[i].length == 3
- 0 ≤ fromi, toi < n
- fromi ≠ toi
- 1 ≤ pricei ≤ 104
- There will not be any multiple flights between two cities
- 0 ≤ src, dst, k < n
- src ≠ dst