OJ练习第154题——到家的最少跳跃次数

本文介绍了一种算法,用于计算一只跳蚤从位置0出发,避开forbidden数组中的位置,按照给定的跳跃规则(a步向前,b步向后,不能连续后退两次),找到到达指定位置x的最少跳跃次数,若无法到达则返回-1。
摘要由CSDN通过智能技术生成

到家的最少跳跃次数

力扣链接:1654. 到家的最少跳跃次数

题目描述

有一只跳蚤的家在数轴上的位置 x 处。请你帮助它从位置 0 出发,到达它的家。

跳蚤跳跃的规则如下:

它可以 往前 跳恰好 a 个位置(即往右跳)。
它可以 往后 跳恰好 b 个位置(即往左跳)。
它不能 连续 往后跳 2 次。
它不能跳到任何 forbidden 数组中的位置。
跳蚤可以往前跳 超过 它的家的位置,但是它 不能跳到负整数 的位置。

给你一个整数数组 forbidden ,其中 forbidden[i] 是跳蚤不能跳到的位置,同时给你整数 a, b 和 x ,请你返回跳蚤到家的最少跳跃次数。如果没有恰好到达 x 的可行方案,请你返回 -1 。

示例

在这里插入图片描述

Java代码

class Solution {
    public int minimumJumps(int[] forbidden, int a, int b, int x) {
        Queue<int[]> queue = new ArrayDeque<int[]>();
        Set<Integer> visited = new HashSet<Integer>();
        queue.offer(new int[]{0, 1, 0});
        visited.add(0);
        int lower = 0, upper = Math.max(Arrays.stream(forbidden).max().getAsInt() + a, x) + b;
        Set<Integer> forbiddenSet = new HashSet<Integer>();
        for(int p : forbidden) {
            forbiddenSet.add(p);
        }
        while(!queue.isEmpty()) {
            int[] arr = queue.poll();
            int position = arr[0], direction = arr[1], step = arr[2];
            if(position == x) return step;

            int nextPosition = position + a;
            int nexDirection = 1;
            if(lower <= nextPosition && nextPosition <= upper && !visited.contains(nextPosition * nexDirection) && ! forbiddenSet.contains(nextPosition)) {
                visited.add(nextPosition * nexDirection);
                queue.offer(new int[]{nextPosition, nexDirection, step + 1});
            }
            if(direction == 1) {
                nextPosition = position - b;
                nexDirection = -1;
                if(lower <= nextPosition && nextPosition <= upper && !visited.contains(nextPosition * nexDirection) && !forbiddenSet.contains(nextPosition)) {
                    visited.add(nextPosition * nexDirection);
                    queue.offer(new int[]{nextPosition, nexDirection, step + 1});
                }
            }
        }
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值