-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathCheapestFlightsWithinKStops.java
More file actions
31 lines (29 loc) · 1.1 KB
/
CheapestFlightsWithinKStops.java
File metadata and controls
31 lines (29 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
Map<Integer, List<int[]>> adj = new HashMap<>();
for (int[] i : flights)
adj.computeIfAbsent(i[0], value -> new ArrayList<>()).add(new int[] { i[1], i[2] });
int[] stops = new int[n];
Arrays.fill(stops, Integer.MAX_VALUE);
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
// {dist_from_src_node, node, number_of_stops_from_src_node}
pq.offer(new int[] { 0, src, 0 });
while (!pq.isEmpty()) {
int[] temp = pq.poll();
int dist = temp[0];
int node = temp[1];
int steps = temp[2];
if (steps > stops[node] || steps > k + 1)
continue;
stops[node] = steps;
if (node == dst)
return dist;
if (!adj.containsKey(node))
continue;
for (int[] a : adj.get(node)) {
pq.offer(new int[] { dist + a[1], a[0], steps + 1 });
}
}
return -1;
}
}