AAlgoLoopSpaced repetition for LeetCode
MEDIUMGraphLeetCode ↗

Cheapest Flights Within K Stops

The key idea

Bellman-Ford fits perfectly: relax all edges exactly k+1 times (k stops means at most k+1 flights). Snapshot the distances before each round so a single round can only extend a path by one more flight, never chain several relaxations within the same round.

Problem

There are n cities connected by some number of flights. You are given an array flights where each flights[i] = [from_i, to_i, price_i] indicates that there is a flight from city from_i to city to_i with cost price_i.

You are also given three integers src, dst, and k. Return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.

A "stop" is an intermediate city on the path, so a route with at most k stops uses at most k + 1 flights.

Constraints

Examples

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1 Output: 200
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1 Output: 700
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0 Output: 500

Complexity

Time: O(k * E) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Graph problems