787 Cheapest Flights Within K Stops

1. Question

There arencities connected by mflights. Each fight starts from city uand arrives at vwith a pricew.
Now given all the cities and fights, together with starting citysrcand the destination dst, your task is to find the cheapest price fromsrctodstwith up tokstops. If there is no such route, output-1.
1
Example 1:
2
3
Input:
4
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
5
src = 0, dst = 2, k = 1
6
7
Output: 200
8
9
Explanation:
10
The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
Copied!
1
Example 2:
2
3
Input:
4
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
5
src = 0, dst = 2, k = 0
6
7
Output: 500
8
9
Explanation:
10
The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.
Copied!

2. Implementation

(1) Breadth First Search
思路:
1
class Solution {
2
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
3
Map<Integer, List<int[]>> adjList = new HashMap();
4
5
for (int[] flight : flights) {
6
int fromCity = flight[0];
7
int toCity = flight[1];
8
int price = flight[2];
9
adjList.putIfAbsent(fromCity, new ArrayList());
10
adjList.get(fromCity).add(new int[] {toCity, price});
11
}
12
13
14
PriorityQueue<int[]> minHeap = new PriorityQueue<int[]>(new Comparator<int[]>() {
15
@Override
16
public int compare(int[] a, int[] b) {
17
return a[2] - b[2];
18
}
19
});
20
minHeap.add(new int[] {src, 0, 0});
21
22
while (!minHeap.isEmpty()) {
23
int[] curInfo = minHeap.remove();
24
int curStop = curInfo[0];
25
// 到达当前的stops 我们已经转了多少个stop
26
int stops = curInfo[1];
27
int curCost = curInfo[2];
28
29
if (curStop == dst) {
30
return curCost;
31
}
32
33
// 只有到达curStop时,转过的stops小于等于K时,我们才继续搜索
34
if (stops <= K && adjList.containsKey(curStop)) {
35
for (int[] nextInfo : adjList.get(curStop)) {
36
int nextStop = nextInfo[0];
37
int price = nextInfo[1];
38
minHeap.add(new int[] {nextStop, stops + 1, curCost + price});
39
}
40
}
41
42
}
43
return -1;
44
}
45
}
Copied!

3. Time & Space Complexity