There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
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.
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
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
This approach involves using a modified DFS algorithm to explore all possible routes from the source to the destination, while pruning unnecessary paths based on constraints (i.e., the number of stops).
K, return as we cannot make more stops.Bellman-Ford is a classic dynamic programming algorithm that can be adapted to this problem with modifications to accommodate the stop constraint.
dp where dp[i][j] represents the minimum cost to reach city j using at most i stops.dp[0][src] to 0 because starting at the source requires no cost, and the rest to infinity.K+1 times to ensure the number of stops doesn't exceed K.K+1 times.A priority queue (min-heap) can help us always extend the least costly current flight path using a variant of Dijkstra's algorithm that's modified to account for the maximum number of allowed stops.
K stops, we found the solution.