本题难度还是不低的,在Medium算是比较高的
关键点:
- 将图存在
Map<Integer, Map<Integer, Integer>>中,比较好调用 - 存储路径在
PriorityQueue中,存储的是可达的路径,将最低price的置于头部,利用类似BFS的方法不断遍历,即可得到最终解
代码如下:
class Solution {public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {Map<Integer, Map<Integer, Integer>> edges = new HashMap<>();for (int[] flight : flights) {if (!edges.containsKey(flight[0])) {edges.put(flight[0], new HashMap<>());}edges.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 start = top[1];int step = top[2];if (start == dst) {return price;}if (step > 0) {if (!edges.containsKey(start)) {continue;}for (Map.Entry<Integer, Integer> tuple : edges.get(start).entrySet()) {pq.offer(new int[] {price + tuple.getValue(), tuple.getKey(), step - 1});}}}return -1;}}
