Graph Theory37 sections · 1633 units
Open in Course

Practice - Cheapest Flights

LeetCode 787 with constraint

Try this practice problem: you have nn cities and mm flights. Each flight goes from city uu to city vv with price ww. Find the cheapest flight from city src to city dst with at most kk stops. This is shortest path with a constraint. You cannot use standard DAG DP because you need to track the number of stops.

Use DP with state dp[u][stops] = cheapest cost to reach city uu with exactly stopsstops stops. Process in BFS order (by number of stops), and relax edges for each stop count.