Budget Trip With Few Layovers

Medium · Topological Sort & Shortest Paths · about 25 min

There are n cities, numbered 0 to n - 1. Each [a, b, price] in flights is a one-way flight from a to b.

You want to fly from src to dst and are willing to change planes in at most max_stops cities in between. Return the cheapest total price of such a trip, or -1 if there is none. If src == dst the price is 0.

  • 1 <= n <= 100, 1 <= price <= 10^4, 0 <= max_stops < n.

Example: budget_trip(4, [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]], 0, 3, 1) → 700 (0 → 1 → 3; the cheaper 0 → 1 → 2 → 3 needs two stops).

Hints

  • k stops in between means at most k + 1 flights. How can you limit the number of flights a price uses?
  • Bellman-Ford's rounds do that: after r rounds you know the cheapest price using at most r flights.
  • Read the old prices from a copy during each round, so one round never chains two flights together.

Learn the pattern first: the Topological Sort & Shortest Paths lesson.

More Topological Sort & Shortest Paths problems