Description
There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w.
Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1.
Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph looks like this:
The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph looks like this:
The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.
Note:
The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
The size of flights will be in range [0, n * (n - 1) / 2].
The format of each flight will be (src, dst, price).
The price of each flight will be in the range [1, 10000].
k is in the range of [0, n - 1].
There will not be any duplicated flights or self cycles.
Solution
给n个城市,城市之间飞行的价格,出发城市和结束城市以及最多换乘几次,问花费最少的花费。
Using a nested map to contain the prices of src to dst.
src->dst->price
. Then using a priorityqueue, which sorts a int[] with{price, dst, stops}, we order it in price ascending. Add {0, src, K + 1} first, which means the prices to src is zero, and we can go to K + 1 cities. Then we start Dijkstra algorithm, it is a greedy approach, find the first element in pq and add his adjacent cities into pq, it we could reach dst, we get the answer.
In the process finding adj, we got city, price, stops information. If we reach dst, return. If stops > 0, it means we could continue flight, that is the condition we could add new cities. Using the map find adjacent cities and prices, then offer(new int[]{prices + adj.get(a), a, stops - 1}).
Code
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
Map<Integer, Map<Integer, Integer>> prices = new HashMap<>();
for (int[] flight : flights){
if (!prices.containsKey(flight[0])){
prices.put(flight[0], new HashMap<Integer, Integer>());
}
prices.get(flight[0]).put(flight[1], flight[2]);
}
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (Integer.compare(a[0], b[0])));
pq.add(new int[]{0, src, K + 1});
while(!pq.isEmpty()){
int[] top = pq.poll();
int price = top[0];
int city = top[1];
int stops = top[2];
if (city == dst){
return price;
}
if (stops > 0){
Map<Integer, Integer> adj = prices.getOrDefault(city, new HashMap<Integer, Integer>());
for (int a : adj.keySet()){
pq.offer(new int[]{price + adj.get(a), a, stops - 1});
}
}
}
return -1;
}
}
Time Complexity: O(n^2)
Space Complexity: O(n)