cheapest flights within k stops solution

Solutions on MaxInterview for cheapest flights within k stops solution by the best coders in the world

showing results for - "cheapest flights within k stops solution"
Michel
25 Feb 2018
1    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
2        Map<Integer, Map<Integer, Integer>> prices = new HashMap<>();
3        for (int[] f : flights) {
4            if (!prices.containsKey(f[0])) prices.put(f[0], new HashMap<>());
5            prices.get(f[0]).put(f[1], f[2]);
6        }
7        Queue<int[]> pq = new PriorityQueue<>((a, b) -> (Integer.compare(a[0], b[0])));
8        pq.add(new int[] {0, src, k + 1});
9        while (!pq.isEmpty()) {
10            int[] top = pq.remove();
11            int price = top[0];
12            int city = top[1];
13            int stops = top[2];
14            if (city == dst) return price;
15            if (stops > 0) {
16                Map<Integer, Integer> adj = prices.getOrDefault(city, new HashMap<>());
17                for (int a : adj.keySet()) {
18                    pq.add(new int[] {price + adj.get(a), a, stops - 1});
19                }
20            }
21        }
22        return -1;
23    }