|
| 1 | +# Cheapest Flights Within K Stops |
| 2 | + |
| 3 | +**Difficulty:** Medium |
| 4 | +**Topics:** Dynamic Programming, Depth-First Search, Breadth-First Search, Graph Theory, Heap (Priority Queue), Shortest Path |
| 5 | +**Tags:** algo-master-75 |
| 6 | + |
| 7 | +**LeetCode:** [Problem 787](https://leetcode.com/problems/cheapest-flights-within-k-stops/description/) |
| 8 | + |
| 9 | +## Problem Description |
| 10 | + |
| 11 | +There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. |
| 12 | + |
| 13 | +You are also given three integers `src`, `dst`, and `k`, return **the cheapest price** from `src` to `dst` with at most `k` stops. If there is no such route, return `-1`. |
| 14 | + |
| 15 | +## Examples |
| 16 | + |
| 17 | +### Example 1: |
| 18 | + |
| 19 | + |
| 20 | + |
| 21 | +``` |
| 22 | +Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 |
| 23 | +Output: 700 |
| 24 | +Explanation: |
| 25 | +The graph is shown above. |
| 26 | +The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. |
| 27 | +Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops. |
| 28 | +``` |
| 29 | + |
| 30 | +### Example 2: |
| 31 | + |
| 32 | + |
| 33 | + |
| 34 | +``` |
| 35 | +Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 |
| 36 | +Output: 200 |
| 37 | +Explanation: |
| 38 | +The graph is shown above. |
| 39 | +The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. |
| 40 | +``` |
| 41 | + |
| 42 | +### Example 3: |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | +``` |
| 47 | +Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 |
| 48 | +Output: 500 |
| 49 | +Explanation: |
| 50 | +The graph is shown above. |
| 51 | +The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. |
| 52 | +``` |
| 53 | + |
| 54 | +## Constraints |
| 55 | + |
| 56 | +- 2 <= n <= 100 |
| 57 | +- 0 <= flights.length <= (n \* (n - 1) / 2) |
| 58 | +- flights[i].length == 3 |
| 59 | +- 0 <= fromi, toi < n |
| 60 | +- fromi != toi |
| 61 | +- 1 <= pricei <= 10^4 |
| 62 | +- There will not be any multiple flights between two cities. |
| 63 | +- 0 <= src, dst, k < n |
| 64 | +- src != dst |
0 commit comments