Dodomeki
Sign in

116. Air Route with a Stop Limit

Medium

An airline network has n airports numbered from 0 to n - 1. Each flight in voos specifies a departure airport, an arrival airport, and its price.

Find the lowest price to travel from origem to destino using at most k stops. A stop is an intermediate airport between two flights, so the route can use at most k + 1 flights. If origem and destino are the same, return 0. If no allowed route exists, return -1.

Example 1
Input: n = 4, voos = [[0, 1, 100], [1, 2, 100], [0, 2, 500], [2, 3, 50]], origem = 0, destino = 3, k = 2
Output: 250
Explanation: The lowest-price route uses the flights 0 → 1 → 2 → 3.
Example 2
Input: n = 3, voos = [[0, 1, 40], [1, 2, 30], [0, 2, 100]], origem = 0, destino = 2, k = 0
Output: 100
Explanation: With zero stops, only a direct flight is allowed.
Example 3
Input: n = 3, voos = [[0, 1, 20]], origem = 0, destino = 2, k = 1
Output: -1
Explanation: There is no flight that reaches the destination airport.
Constraints
  • 1 <= n <= 100
  • 0 <= voos.length <= 2000
  • Each flight has the form [a, b, preco], with 0 <= a, b < n and a != b.
  • 1 <= preco <= 10^6
  • 0 <= origem, destino < n
  • 0 <= k <= n - 1
GraphsDynamic programming
Caso 1
n =
4
voos =
[[0,1,100],[1,2,100],[0,2,500],[2,3,50]]
origem =
0
destino =
3
k =
2
Expected =
250
Caso 2
n =
3
voos =
[[0,1,40],[1,2,30],[0,2,100]]
origem =
0
destino =
2
k =
0
Expected =
100
Caso 3
n =
3
voos =
[[0,1,20]]
origem =
0
destino =
2
k =
1
Expected =
-1

Run checks these 3 cases. Submit runs all 12, including hidden ones.