Repository navigation
Expand file tree
/
Copy pathCheapestFlightKHops.java
More file actions
60 lines (49 loc) · 1.71 KB
/
Copy pathCheapestFlightKHops.java
File metadata and controls
60 lines (49 loc) · 1.71 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
public class CheapestFlightKHops {
public static int findCheapestFlight(int n, int[][] flights, int src, int dest, int k) {
List<List<int[]>> graph = new ArrayList<>();
for(int i=0; i<n; i++) {
graph.add(new ArrayList<>());
}
for(int[] flight: flights) {
int from = flight[0];
int to = flight[1];
int cost = flight[2];
graph.get(from).add(new int[]{to, cost});
}
//{city,kstops} => cost
int[][] dist = new int[n][k+2];
for(int[] row: dist) {
Arrays.fill(row, Integer.MAX_VALUE);
}
dist[src][0] = 0;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
pq.offer(new int[]{0, src, 0});
while(!pq.isEmpty()) {
int[] node = pq.poll();
int cost = node[0];
int fromCity = node[1];
int flightsUsed = node[2];
if(fromCity == dest) {
return cost;
}
if(flightsUsed == k+1) {
continue;
}
for(int[] edge: graph.get(fromCity)) {
int nextCity = edge[0];
int nextCost = edge[1];
int newCost = cost + nextCost;
int newFlightsUsed = flightsUsed + 1;
if(newCost < dist[nextCity][newFlightsUsed]) {
dist[nextCity][newFlightsUsed] = newCost;
pq.offer(new int[]{newCost, nextCity, newFlightsUsed});
}
}
}
return -1;
}
}