[Leetcode学习-java]Cheapest Flights Within K Stops(K次到达目的地最便宜航程)

问题:

难度: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 city 0 to city 2 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];
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值