Python coding

Budget trip with a stop limit

There are n cities numbered 0 to n - 1. Each entry of flights is [origin, target, price], a one-way flight. Return the lowest total price to travel from src to dst making at most k stops in between (that is, taking at most k + 1 flights), or -1 if no such route exists. If src == dst, the trip is free.

Prices are positive integers; the same flight may appear twice.

Besides the tests, one large input (100 cities, 1,000 flights) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • cheapest_fare(3, [[0,1,40],[1,2,30],[0,2,90]], 0, 2, 1) → 70
  • cheapest_fare(3, [[0,1,40],[1,2,30],[0,2,90]], 0, 2, 0) → 90
  • cheapest_fare(4, [[0,1,1],[1,2,1],[2,3,1]], 0, 3, 1) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A stop limit breaks plain Dijkstra: a cheap route with too many stops can block a pricier one that fits. Track flights used, not just price.

Hint 2

Run k + 1 rounds of Bellman-Ford relaxation. In each round, read from a copy of the previous round's prices, so every round adds at most one flight.

Solution and why it works
pythonO(k·E), E = len(flights) · O(n)
def cheapest_fare(n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:
    INF = float("inf")
    cost = [INF] * n                     # cost[v] = cheapest price to v so far
    cost[src] = 0
    for _ in range(k + 1):               # round i allows routes of up to i flights
        nxt = cost[:]                    # read last round only: one more flight per round
        for u, v, price in flights:
            if cost[u] + price < nxt[v]:
                nxt[v] = cost[u] + price
        cost = nxt
    return -1 if cost[dst] == INF else cost[dst]

After round i, cost[v] is the cheapest price to reach v with at most i flights, so k + 1 rounds answer the question in O(k·E). The copy is the whole trick: relaxing in place lets one round chain several flights when the list happens to be in route order (0→1→2→3 with k = 0). Plain Dijkstra fails too: it keeps one price per city, so a cheap route with too many stops hides a valid one.