本题难度还是不低的,在Medium算是比较高的
    关键点

    1. 将图存在Map<Integer, Map<Integer, Integer>>中,比较好调用
    2. 存储路径在PriorityQueue中,存储的是可达的路径,将最低price的置于头部,利用类似BFS的方法不断遍历,即可得到最终解

    代码如下:

    1. class Solution {
    2. public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
    3. Map<Integer, Map<Integer, Integer>> edges = new HashMap<>();
    4. for (int[] flight : flights) {
    5. if (!edges.containsKey(flight[0])) {
    6. edges.put(flight[0], new HashMap<>());
    7. }
    8. edges.get(flight[0]).put(flight[1], flight[2]);
    9. }
    10. PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (Integer.compare(a[0], b[0])));
    11. pq.add(new int[] {0, src, K + 1});
    12. while (!pq.isEmpty()) {
    13. int[] top = pq.poll();
    14. int price = top[0];
    15. int start = top[1];
    16. int step = top[2];
    17. if (start == dst) {
    18. return price;
    19. }
    20. if (step > 0) {
    21. if (!edges.containsKey(start)) {
    22. continue;
    23. }
    24. for (Map.Entry<Integer, Integer> tuple : edges.get(start).entrySet()) {
    25. pq.offer(new int[] {price + tuple.getValue(), tuple.getKey(), step - 1});
    26. }
    27. }
    28. }
    29. return -1;
    30. }
    31. }