Cheapest Flights Within K Stops

Medium Advanced graphs AI round

The n cities are numbered from 0 to n - 1. Each entry [from, to, price] of flights is a one-way flight from city from to city to that costs price.

A trip from src to dst takes flights one after another, each leaving from the city where the one before landed. Each city it lands in before dst is a stop, so a trip with k stops takes k + 1 flights.

Return the cheapest price of a trip from src to dst with at most k stops, or -1 if there is none. When src and dst are the same city, no flight is needed and the price is 0.

Example 1

Input: n = 5, flights = [[0,1,40],[1,4,40],[0,2,10],[2,3,10],[3,4,10],[0,4,100]], src = 0, dst = 4, k = 1
Output: 80

The cheapest trip, 0 → 2 → 3 → 4 for 30, stops at 2 and 3: one stop too many. With one stop, 0 → 1 → 4 costs 80, less than the direct flight for 100.

Example 2

Input: n = 5, flights = [[0,1,40],[1,4,40],[0,2,10],[2,3,10],[3,4,10],[0,4,100]], src = 0, dst = 4, k = 2
Output: 30

Example 3

Input: n = 3, flights = [[0,1,5],[1,0,5]], src = 0, dst = 2, k = 2
Output: -1

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ flights.length ≤ 2000
  • flights[i] = [from, to, price], with 0 ≤ from, to < n, from ≠ to and 1 ≤ price ≤ 10⁴
  • No two flights go from the same city to the same city
  • 0 ≤ src, dst < n
  • 0 ≤ k < n

More Advanced graphs

All Advanced graphs problems