Created
March 24, 2020 18:17
-
-
Save wushbin/3c88e1745a3266fd941585b8b001ecb1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) { | |
| Map<Integer, Map<Integer, Integer>> graph = new HashMap<>(); | |
| for (int[] flight : flights) { | |
| if (!graph.containsKey(flight[0])) { | |
| graph.put(flight[0], new HashMap<>()); | |
| } | |
| graph.get(flight[0]).put(flight[1], flight[2]); | |
| } | |
| PriorityQueue<int[]> queue = new PriorityQueue<>((a, b)->(Integer.compare(a[0], b[0]))); | |
| queue.offer(new int[]{0, src, 0}); | |
| while(!queue.isEmpty()) { | |
| int[] curr = queue.poll(); | |
| int cost = curr[0]; | |
| int loc = curr[1]; | |
| int step = curr[2]; | |
| if (loc == dst) { | |
| return cost; | |
| } | |
| Map<Integer, Integer> neighbors = graph.get(loc); | |
| if (neighbors == null || step > K) { | |
| continue; | |
| } | |
| for (Map.Entry<Integer, Integer> entry : graph.get(loc).entrySet()) { | |
| int nextLoc = entry.getKey(); | |
| int nextCost = entry.getValue(); | |
| queue.offer(new int[]{cost + nextCost, nextLoc, step + 1}); | |
| } | |
| } | |
| return -1; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment