leetcode 1345. Jump Game IV | 1345. 跳跃游戏 IV(BFS)

2023-05-16

题目

https://leetcode.com/problems/jump-game-iv/
在这里插入图片描述

题解

好久没做 hard 了,今天时间多,挑战一下。用 lqy 同学的话说,这题叫做 “苦难题”,哈哈哈。

暴力解其实不难,就是个带 seen 数组的 BFS,看草稿吧~
在这里插入图片描述

class Solution {
    public int minJumps(int[] arr) {
        Map<Integer, Set<Integer>> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            Set<Integer> set = map.getOrDefault(arr[i], new HashSet<>());
            set.add(i);
            map.put(arr[i], set);
        }

        Set<Integer> seen = new HashSet<>();
        LinkedList<Integer> queue = new LinkedList<>();
        queue.add(0);
        int jump = 0;
        
        while (true) {
            LinkedList<Integer> nextQueue = new LinkedList<>();
            
            while (!queue.isEmpty()) {
                Integer index = queue.poll();
                seen.add(index);
                if (index == arr.length - 1) return jump;

                if (index - 1 >= 0) {
                    if (!seen.contains(index - 1)) nextQueue.add(index - 1);
                    else map.get(arr[index]).remove(index - 1);
                }
                if (index + 1 < arr.length && !seen.contains(index + 1)) {
                    if (!seen.contains(index + 1)) nextQueue.add(index + 1);
                    else map.get(arr[index]).remove(index + 1);
                }
                for (Integer i : map.get(arr[index])) {
                    if (!seen.contains(i)) nextQueue.add(i);
//                    else map.get(arr[i]).remove(i);
                }
                map.get(arr[index]).clear();
            }
            queue = nextQueue;
            jump++;
        }
    }
}

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

leetcode 1345. Jump Game IV | 1345. 跳跃游戏 IV(BFS) 的相关文章

  • Python正则表达式之 - ?: / ?= / ?!

    用圆括号将所有选择项括起来 xff0c 相邻的选择项之间用 分隔 但用圆括号会有一个副作用 xff0c 使相关的匹配会被缓存 xff0c 此时可用 放在第一个选项前来消除这种副作用 其中 是非捕获元之一 xff0c 还有两个非捕获元是 61
  • Python教程:无参装饰器

    一 xff1a 储备知识 1 args xff0c kwargs span class token keyword def span span class token function index span span class token
  • 面向对象:类关系(泛化/实现/依赖/关联/聚合/组合)

    泛化 泛化 xff0c 也称作继承关系 指面向对象中派生类与基类之间的关系 xff0c 一个类 xff08 称为子类 子接口 xff09 继承另外的一个类 xff08 称为父类 父接口 xff09 的功能 指ClassA为ClassB Cl
  • webpack基本概念及使用

    webpack是什么 xff0c 用来干什么 xff1f webpack 是一个用于现代 JavaScript 应用程序的静态模块打包工具 xff1b webpack的下载安装 官网文档地址 xff1a https webpack js o

随机推荐