问题:
难度:medium
说明:
这是一个典型的Bellman-Ford算法,输入一个起始点和终点,K(可以中转次数),两个地点之间的机票二维数组,求从起始点到终点最便宜机票费用。
问题链接:https://leetcode.com/problems/cheapest-flights-within-k-stops/
相关问题:
P1411-树:https://blog.csdn.net/qq_28033719/article/details/106121253
输入范围:
The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 1.
The size of flights will be in range [0, n * (n - 1) / 2].
The format of each flight will be (src, dst, price).
The price of each flight will be in the range [1, 10000].
k is in the range of [0, n - 1].
There will not be any duplicated flights or self cycles.
输入案例:
Example 1: Input: n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]] src = 0, dst = 2, k = 1 Output: 200 Explanation: The graph looks like this: The cheapest price from city0
to city2
with at most 1 stop costs 200, as marked red in the picture.
我的代码:
多了一个允许步数K,那么需要把之前的数组值先存放,避免步数重叠了,这里可以使用滚动数组实现,我有两种方案,先放出滚动数组。
滚动数组的写法:https://blog.csdn.net/qq_28033719/article/details/106501253
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[][] dis = new int[2][n];
int len = flights.length;
int index = 0;
// 1、先初始化图,n<=100,价格<=10000,n * 价格所以就这个当最大值
for(int i = 0;i < 2;i ++)
for(int j = 0;j < n;j ++)
if(j != src) dis[i][j] = 1000000;
// 2、进行松弛操作
for(int i = 0;i <= K;i ++) {
// 滚动数组的做法,需要两个指向坐标
index ^= 1;
int prev = index ^ 1;
for(int j = 0;j < len;j ++) {
int[] edge = flights[j];
// 这里相对下面的进行逻辑修改一下,滚动index是上两次
dis[index][edge[1]] = Math.min(dis[index][edge[1]],dis[prev][edge[0]] + edge[2]);
}
}
return dis[index][dst] >= 1000000 ? -1 : dis[index][dst];
}
}
不使用滚动数组的方法:
这个方法其实一样意思,但是需要不断地dis.clone(),所以没有滚动数组节省时间。
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
int[] dis = new int[n];
int len = flights.length;
int max = 1000000;
for(int i = 0;i < n;i ++) if(i != src) dis[i] = max;
for(int i = 0;i <= K;i ++) {
int[] temp = dis.clone();
for(int j = 0;j < len;j ++) {
int[] edge = flights[j];
temp[edge[1]] = Math.min(temp[edge[1]],dis[edge[0]] + edge[2]);
}
dis = temp;
}
return dis[dst] >= max ? -1 : dis[dst];
}
}