这题给了很多张机票,让求从出发城市到到达城市最便宜的票价。但有一个限制条件就是不能超过K次转机。这道题非常火热,考察图论,考察Dikjstra基本功.
思种是从起始城市出发,把它第一步能到的城市都放到一个heap里面。然后每次从heap里取出来的永远都是票价最小的,所以我们只要第一次从heap里取出来我们的目标城市,那一定是票价最低的。
如果我们第二次出现在同一个城市,还需要把原来的老路重新走一遍吗?(还需要沿着它的flight重新expand 一遍它的下游吗)这里如果第二次用的转机少,或者用的钱少,都要继续 expand下游。如果第二次机用的转机次数又多又贵就没必要看了。
一个做法是状态用城市+转机次数表示。
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] graph = new int[n][n];
for (int[] flight : flights) {
graph[flight[0]][flight[1]] = flight[2];
}
Queue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(o -> o[1]));
if (src == dst) return 0;
Map<Integer, Integer> visited = new HashMap<>();
queue.offer(new int[]{src, 0, 0}); // [cityId, moneySpent, stopUsed];
visited.put(src, 0);
while (!queue.isEmpty()) {
int[] info = queue.poll();
int start = info[0], moneySpent = info[1], stopUsed = info[2];
if (start == dst) return moneySpent;
for (int i = 0; i < n; i++) {
if (stopUsed >= K && i != dst) continue;
if (graph[start][i] == 0) continue;
if (visited.containsKey(1000 * (stopUsed + 1) + i)) {
if (visited.get(1000 * (stopUsed + 1) + i) <= moneySpent + graph[start][i]) continue;
}
visited.put(1000 * (stopUsed + 1) + i, moneySpent + graph[start][i]);
queue.offer(new int[]{i, moneySpent + graph[start][i], stopUsed + 1});
}
}
return -1;
}
另一个做法是只要转机次数还没到,就统统expand丢进去。
第二个做法的code; 时间复杂度也是O(kN^2)
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] graph = new int[n][n];
for (int[] flight : flights) {
graph[flight[0]][flight[1]] = flight[2];
}
Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(o -> o[1]));
if (src == dst) return 0;
minHeap.offer(new int[]{src, 0, 0});
while (!minHeap.isEmpty()) {
int[] stopOver = minHeap.poll();
if (stopOver[0] == dst) return stopOver[1];
int s = stopOver[0];
for (int i = 0; i < n; i++) {
if (s == i || graph[s][i] == 0) continue;
if (i != dst && stopOver[2] == K) continue;
minHeap.offer(new int[]{i, stopOver[1] + graph[s][i], stopOver[2] + 1});
}
}
return -1;
}
这题另外一种做法是DP
DP也是非常直接暴力,时间复杂度是O(KN^2) 或者 O(K(V+E))
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] dp = new int[n][K + 2];
int[][] graph = buildGraph(flights, n);
for (int stop = 0; stop <= K + 1; stop++) {
if (stop == 0) {
for (int city = 0; city < n; city++) {
if (city != src) {
dp[city][stop] = 2000000;
}
}
} else {
for (int city = 0; city < n; city++) {
dp[city][stop] = dp[city][stop - 1];
for (int prev = 0; prev < n; prev++) {
if (graph[prev][city] == 0) continue;
dp[city][stop] = Math.min(dp[city][stop], dp[prev][stop - 1] + graph[prev][city] );
}
}
}
}
return dp[dst][K + 1] == 2000000 ? -1 : dp[dst][K + 1];
}
private int[][] buildGraph(int[][] flight, int n) {
int[][] graph = new int[n][n];
for (int[] ticket : flight) {
graph[ticket[0]][ticket[1]] = ticket[2];
}
return graph;
}
这题有一个很有名的follow up就是打印路径。打印路径的时候需要记住上一次是从哪来的。这里要注意的是,对每个city,要记住在第K次到达他时是从哪里来的。 不能只是记住是从哪个城市过来的,要记处第K步到达这个城市时是从哪一个城市过来的。