AlgoFrames

Cheapest flights within k stops

Standard · Write code · about 15 min

There are n cities and one-way flights, where flights[i] = [from, to, price]. Return the cheapest price from src to dst using at most k stops, or -1 when no such route exists.

A route with k stops uses k + 1 flights.

Example 1

Input:

[4,[[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]],0,3,1]

Output:

700

0 → 1 → 3 costs 700. The cheaper 0 → 1 → 2 → 3 needs 2 stops.

Example 2

Input:

[3,[[0,1,100],[1,2,100],[0,2,500]],0,2,1]

Output:

200

One stop at city 1 is allowed.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ flights.length ≤ 4,950
  • 1 ≤ price ≤ 10^4
  • 0 ≤ src, dst, k < n
  • src ≠ dst

Learn the idea first: Bellman-Ford and negative edges, a visual lesson.

More Bellman-Ford and negative edges problems