787. Cheapest Flights Within K Stops

15 阅读1分钟

image.png

Solution BFS

  • we will perform a level-wise BFS iteration over the nodes
  • level limited by k
  • cost[] stores the minimum price to reach each node
  • if next adj costs more than min, dont explore

image.png

class Solution {
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
        // build graph
        // <from, <to, cost of 'from->to'> >
        Map<Integer, Map<Integer, Integer>> graph = new HashMap<>();
        for (int[] flight : flights) {
            int from = flight[0], to = flight[1], cost = flight[2];
            if (!graph.containsKey(from)) {
                graph.put(from, new HashMap<>());
            }
            graph.get(from).put(to, cost);
        }

        // Each element is [currentCity, costSoFar] (costSoFar: on each bfs level)
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[] {src, 0});

        int stops = 0;

        // minCost[i] holds the minimum cost to reach city 'i'
        int[] minCost = new int[n];
        Arrays.fill(minCost, Integer.MAX_VALUE);

        while (stops <= k && !queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                int[] cur = queue.poll();
                int curCity = cur[0];
                int curCost = cur[1];

                // if city has no outgoing flight
                if (!graph.containsKey(curCity)) {
                    continue;
                }

                // bfs
                for (Map.Entry<Integer, Integer> entry : graph.get(curCity).entrySet()) {
                    int nextCity = entry.getKey();
                    int cost = entry.getValue();

                    // If the new cost is cheaper, consider this path and add to queue
                    if (minCost[nextCity] > curCost + cost) {
                        minCost[nextCity] = curCost + cost;
                        queue.offer(new int[] { nextCity, minCost[nextCity] });
                    }
                }
            }
            stops++;
        }
        
        // no such route -> -1
        return minCost[dst] == Integer.MAX_VALUE ? -1 : minCost[dst];
    }
}