题目来源:https://leetcode-cn.com/problems/cheapest-flights-within-k-stops/
大致题意:
给定一个有向图(保证无环),取出源点到目的点在 k+1 步内的最短路径
思路
DP
使用 dp[i][j] 表示第 i 步到达位置 j 的最短路径长度。
那么有 dp[i][j] = min(dp[i-1][x] + cost),其中 x 为与 j 相连边的出发点,cost为该边长度
那么初始时有 dp[0][src] = 0
最后的答案为 dp[i][dst] 中的最小值
代码:
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
// 预设一个最大值
final int INF = 10000*101 + 1;
// k 个中转可以有 k+1 个航班,初始化时 0 也占一位,故第一维大小为 k+2
// dp[i][j] 表示第 i 步到达位置 j 的最短路径长度
int[][] dp = new int[k+2][n];
int ans = INF;
// 初始化
for (int[] d : dp) {
Arrays.fill(d, INF);
}
dp[0][src] = 0;
// dp[i][j] = min(dp[i-1][costSum] + costOfEdge)
for (int i = 1; i <= k+1; i++) {
for (int[] flight : flights) {
int from = flight[0];
int to = flight[1];
int cost = flight[2];
dp[i][to] = Math.min(dp[i][to], dp[i-1][from] + cost);
}
ans = Math.min(dp[i][dst], ans);
}
return ans == INF ? -1 : ans;
}