LCP 09. 最小跳跃次数

为了给刷题的同学一些奖励,力扣团队引入了一个弹簧游戏机。游戏机由 N 个特殊弹簧排成一排,编号为 0 到 N-1。初始有一个小球在编号 0 的弹簧处。若小球在编号为 i 的弹簧处,通过按动弹簧,可以选择把小球向右弹射 jump[i] 的距离,或者向左弹射到任意左侧弹簧的位置。也就是说,在编号为 i 弹簧处按动弹簧,小球可以弹向 0 到 i-1 中任意弹簧或者 i+jump[i] 的弹簧(若 i+jump[i]>=N ,则表示小球弹出了机器)。小球位于编号 0 处的弹簧时不能再向左弹。

为了获得奖励,你需要将小球弹出机器。请求出最少需要按动多少次弹簧,可以将小球从编号 0 弹簧弹出整个机器,即向右越过编号 N-1 的弹簧。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zui-xiao-tiao-yue-ci-shu
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

广度优先搜索

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

class Solution {
    public int minJump(int[] jump) {
        if (jump == null || jump.length == 0) {
            return 0;
        }
        Set<Integer> visited = new HashSet<>();
        Queue<Info> queue = new LinkedList<>();
        queue.offer(new Info(0, 0));
        int left = 1;
        while (!queue.isEmpty()) {
            Info node = queue.poll();
            if (node.x >= jump.length) {
                return node.step;
            }
            if (!visited.contains(node.x + jump[node.x])) {
                visited.add(node.x + jump[node.x]);
                queue.offer(new Info(node.x + jump[node.x], node.step + 1));
            }
            for (int i = left; i < node.x; ++i) {
                if (!visited.contains(i)) {
                    visited.add(i);
                    queue.offer(new Info(i, node.step + 1));
                }
            }
            left = Math.max(left, node.x + 1);
        }
        return -1;
    }
}

class Info {
    int x;
    int step;

    public Info(int x, int step) {
        this.x = x;
        this.step = step;
    }
}

动态规划


posted @   Tianyiya  阅读(55)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示