Leetcode 787: Cheapest Flights Within K Stops

grid47
grid47
Exploring patterns and algorithms
Aug 20, 2024 6 min read

A map where the cheapest flight path is calculated, glowing softly as the optimal path is found.
Solution to LeetCode 787: Cheapest Flights Within K Stops Problem

You are given a number of cities and a list of flights between them. Each flight has a price and connects two cities. You need to find the cheapest route from a given source city to a destination city with at most a certain number of stops. If no such route exists, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of the number of cities, the list of flights, the source city, the destination city, and the maximum number of stops allowed.
Example: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Constraints:
• 1 <= n <= 100
• 0 <= flights.length <= (n * (n - 1) / 2)
• flights[i].length == 3
• 0 <= fromi, toi < n
• fromi != toi
• 1 <= pricei <= 104
• There will not be any multiple flights between two cities.
• 0 <= src, dst, k < n
• src != dst
Output: The output should be the cheapest price to travel from the source city to the destination city with at most k stops. If no such route exists, return -1.
Example: Output: 700
Constraints:
• The output will be an integer representing the cheapest price.
Goal: The goal is to find the cheapest price between the source and destination cities with at most k stops.
Steps:
• Use the Bellman-Ford algorithm to find the shortest path.
• Run the algorithm k+1 times to account for at most k stops.
• Track the minimum price for each flight path.
Goal: Make sure to handle edge cases such as no available flights, flights with more than k stops, and large numbers of cities and flights.
Steps:
• Ensure the number of cities (n) does not exceed 100.
• Ensure the flights array does not contain duplicate entries.
Assumptions:
• You can assume there are no direct flights from the source to destination if the source is not equal to the destination.
• Flights may have different costs and may be one-way only.
Input: 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
Explanation: In this example, we need to find the cheapest route from city 0 to city 3 with at most one stop. The cheapest route is through city 1 with a total cost of 700.

Input: Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Explanation: The cheapest route from city 0 to city 2 with one stop is through city 1, costing a total of 200.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus