Menu
CoddyTech

Cheapest Flights Within K Stops

There are n cities, numbered 0 to n-1, and a list of one way flights: flights[i] = [from, to, price] is a flight from city from to city to that costs price.

Return the lowest total price of a trip from src to dst that makes at most k stops on the way, which means at most k+1 flights. If no such trip exists, return -1.

Function

findCheapestPrice(n: integer, flights: integer-2d-array, src: integer, dst: integer, k: integer) → integer
ninteger
the number of cities
flightsinteger-2d-array
the one way flights, each as [from, to, price]
srcinteger
the city where the trip starts
dstinteger
the city where the trip ends
kinteger
the most stops allowed between src and dst
Returnsinteger
the lowest price of a trip with at most k stops, or -1

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ flights.length ≤ 4500
  • flights[i] = [from, to, price] with 0 ≤ from, to < n and from ≠ to
  • 1 ≤ price ≤ 104
  • No two flights share both from and to.
  • 0 ≤ src, dst < n and src ≠ dst
  • 0 ≤ k < n

Examples

Input
n = 4flights = [[0, 1, 50], [1, 2, 50], [2, 3, 50], [0, 2, 200], [1, 3, 180]]src = 0dst = 3k = 1
Output
230
Explanation
One stop allows two flights: 0 → 1 → 3 costs 50 + 180 = 230 and 0 → 2 → 3 costs 200 + 50 = 250. The cheaper 0 → 1 → 2 → 3 makes two stops.
challenge icon

Follow-up

How would you return the cities on the cheapest trip as well as its price?

Reset code
def findCheapestPrice(n, flights, src, dst, k):
    # Write code here

Test #1

Test #2

Test #3

Arguments

n = 4
flights = [[0, 1, 50], [1, 2, 50], [2, 3, 50], [0, 2, 200], [1, 3, 180]]
src = 0
dst = 3
k = 1

Expected Output

230