711970. Cheapest Flights Within K Stops
Here is the detailed Markdown blog post for the "Cheapest Flights Within K Stops" problem:
Cheapest Flights Within K Stops
Summary
Given a set of flights with prices and k, find the cheapest flight within k stops from a starting city. The graph represents flights between cities, where each edge has a weight (price). We need to find the shortest path in this graph that passes through at most k intermediate cities.
Detailed Explanation
To solve this problem, we can use Breadth-First Search (BFS) algorithm. BFS is suitable for this problem because it explores all nodes at the present depth before moving on to nodes at the next depth level, which means it will find the shortest path within k stops.
Here's a step-by-step breakdown of the solution:
- Initialize a queue with the starting city.
- Create a visited set to keep track of visited cities.
- While the queue is not empty:
- Dequeue a city from the queue.
- If the city has not been visited before, mark it as visited and enqueue all its unvisited neighbors.
- Keep track of the cheapest flight within k stops.
Time complexity: O(E + V), where E is the number of edges and V is the number of vertices (cities). Space complexity: O(V) for storing visited cities in a set.
Optimized Solutions
Java
import java.util.*;
public class CheapestFlights {
public int cheapestFlight(int[][] flights, int src, int dest, int k) {
Map<Integer, List<int[]>> graph = new HashMap<>();
for (int[] flight : flights) {
if (!graph.containsKey(flight[0])) {
graph.put(flight[0], new ArrayList<>());
}
graph.get(flight[0]).add(flight);
}
int minCost = Integer.MAX_VALUE;
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{src, 0});
Set<Integer> visited = new HashSet<>();
while (!queue.isEmpty()) {
int[] city = queue.poll();
if (city[0] == dest && city[1] <= k) {
minCost = Math.min(minCost, city[1]);
}
if (city[1] > k || visited.contains(city[0])) continue;
visited.add(city[0]);
for (int[] neighbor : graph.getOrDefault(city[0], new ArrayList<>())) {
queue.add(new int[]{neighbor[2], city[1] + neighbor[1]});
}
}
return minCost == Integer.MAX_VALUE ? -1 : minCost;
}
}