Cheapest Flights Within K Stops šŸŽÆ

beginner
22 min

Cheapest Flights Within K Stops šŸŽÆ

Welcome to this exciting lesson on Data Structures and Algorithms where we'll dive into the topic of finding the cheapest flights within K stops! This lesson is designed for both beginners and intermediates, so let's get started! šŸ“

What are we trying to achieve? šŸ’”

In this problem, we are given a list of flights between cities and their costs. We need to find the minimum cost to travel from one city (src) to another (dest) with at most K stops. Let's break it down!

Understanding the Problem šŸ“

  • n cities connected by m flights
  • Each flight has a cost and an associated number of stops (1 or 2)
  • src and dest are two different cities
  • K is the maximum number of stops allowed for our journey

Algorithm Design šŸ’”

The solution to this problem lies in a combination of graph traversal and dynamic programming. We will use Depth-First Search (DFS) to explore the graph and Dynamic Programming (DP) to optimize the cost.

Dynamic Programming šŸ“

We will create a 2D array dp[n][K+1] to store the minimum cost to reach each city with K stops remaining. The base case is when K == 0, the cost would be 0 if the city is dest and āˆž otherwise.

Implementing the Solution šŸ’”

Now let's write the code for this problem. We'll use Python as our language for this example.

python
def find_cheapest_flights(n, flights, src, dest, K): # Initialize the dp array dp = [[float('inf')] * (K + 1) for _ in range(n)] # Base case: no stops left dp[src][0] = 0 for flight in flights: city1, city2, cost, stops = flight for k in range(stops, K + 1): if dp[city1][k - stops] != float('inf') and dp[city2][k] > dp[city1][k - stops] + cost: dp[city2][k] = dp[city1][k - stops] + cost return min(dp[dest][K]) if dp[dest][K] != float('inf') else -1

Putting it all together šŸ’”

Let's test our function with a sample dataset:

python
flights = [ (0, 1, 100, 1), (1, 2, 50, 1), (0, 2, 200, 2), (2, 1, 10, 2) ] n = 3 src = 0 dest = 2 K = 1 print(find_cheapest_flights(n, flights, src, dest, K)) # Output: 110

Quiz Time! šŸ’”

Quick Quiz
Question 1 of 1

What does the base case in our Dynamic Programming solution represent?

Remember, understanding the problem and algorithm is the key to solving it! Practice this problem with different datasets and improve your skills in Data Structures and Algorithms. Happy coding! šŸ¤–

Cheapest Flights Within K Stops šŸŽÆ - Data Structures and Algorithms | CodeYourCraft | CodeYourCraft