AlgoMaster Logo

Cheapest Flights Within K Stops

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Modified Depth-First Search with Pruning

Intuition:

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).

  1. Use a recursive DFS method to visit all nodes.
  2. If the number of stops exceeds K, return as we cannot make more stops.
  3. Track the currently accumulated cost; if it exceeds the known minimum cost for reaching the destination, prune that path.
  4. Use the adjacency list to explore every neighboring node recursively.
  5. Update the result whenever a valid path with a cost lower than the current known minimum is found.

Code:

2. Bellman-Ford Algorithm (Dynamic Programming)

Intuition:

Bellman-Ford is a classic dynamic programming algorithm that can be adapted to this problem with modifications to accommodate the stop constraint.

  1. Use a 2D DP array dp where dp[i][j] represents the minimum cost to reach city j using at most i stops.
  2. Initialize dp[0][src] to 0 because starting at the source requires no cost, and the rest to infinity.
  3. Update costs for flights up to K+1 times to ensure the number of stops doesn't exceed K.

Code:

3. Dijkstra's Algorithm

Intuition:

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.

  1. Use a priority queue to always select the current minimum cost path.
  2. Keep track of costs and number of stops made.
  3. If we reach a destination before exceeding K stops, we found the solution.
  4. Use an array to store the minimum cost to reach each city within a certain number of stops.

Code: