There are n
cities connected by m
flights. Each flight 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 city0
to city2
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 city0
to city2
with at most 0 stop costs 500, as marked blue in the picture.
1 class Solution { 2 public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { 3 Map<Integer, Map<Integer, Integer>> prices = new HashMap<>(); 4 for (int[] f : flights) { 5 if (!prices.containsKey(f[0])) prices.put(f[0], new HashMap<>()); 6 prices.get(f[0]).put(f[1], f[2]); 7 } 8 Queue<int[]> pq = new PriorityQueue<>((a, b) -> (Integer.compare(a[0], b[0]))); 9 pq.add(new int[] {0, src, k + 1}); 10 while (!pq.isEmpty()) { 11 int[] top = pq.remove(); 12 int price = top[0]; 13 int city = top[1]; 14 int stops = top[2]; 15 if (city == dst) return price; 16 if (stops > 0) { 17 Map<Integer, Integer> adj = prices.getOrDefault(city, new HashMap<>()); 18 for (int a : adj.keySet()) { 19 pq.add(new int[] {price + adj.get(a), a, stops - 1}); 20 } 21 } 22 } 23 return -1; 24 } 25 }