leetcode 1345. 跳跃游戏 IV

题目:1345. 跳跃游戏 IV - 力扣(LeetCode)

经典bfs,关键是建立所有"arr[i] == arr[j]"的连接。我的做法是用额外的存储,记录每个整数的前后整数都是哪个,再对数组排序。每个整数搜索的下个节点就是prev、next和数组中相邻且相等的整数:

cpp 复制代码
struct Node {
    int val;
    int index;
    int jumps = -1;
    Node* prev = nullptr;
    Node* next = nullptr;
    Node(int val) {
        this->val = val;
    }
};
bool myComp(Node* a, Node* b) {
    return a->val < b->val;
}
class Solution {
public:
    int minJumps(vector<int>& arr) {
        size_t n = arr.size();
        if (n <= 1) {
            return 0;
        }
        vector<Node*> nodes(n);
        for (int i = 0; i < n; i++) {
            nodes[i] = new Node(arr[i]);
            if (i > 0) {
                nodes[i - 1]->next = nodes[i];
                nodes[i]->prev = nodes[i - 1];
            }
        }
        list<Node*> bfs;
        bfs.push_back(nodes[0]);
        nodes[0]->jumps = 0;
        Node* tail = nodes[n - 1];
        sort(nodes.begin(), nodes.end(), myComp);
        for (int i = 0; i < n; i++) {
            nodes[i]->index = i;
        }
        
        Node* t;
        int i;
        while (!bfs.empty()) {
            t = bfs.front();
            bfs.pop_front();
            i = t->index - 1;
            while (i >= 0 && nodes[i]->val == t->val && nodes[i]->jumps == -1) {
                nodes[i]->jumps = t->jumps + 1;
                bfs.push_back(nodes[i]);
                i--;
            }
            i = t->index + 1;
            while (i < n && nodes[i]->val == t->val && nodes[i]->jumps == -1) {
                nodes[i]->jumps = t->jumps + 1;
                bfs.push_back(nodes[i]);
                i++;
            }
            if (t->prev && t->prev->jumps == -1) {
                t->prev->jumps = t->jumps + 1;
                bfs.push_back(t->prev);
            }
            if (t->next && t->next->jumps == -1) {
                t->next->jumps = t->jumps + 1;
                bfs.push_back(t->next);
            }
            if (tail->jumps != -1) {
                return tail->jumps;
            }
        }
        return (int) n - 1;
    }
};
相关推荐
狐572 小时前
2026-01-22-LeetCode刷题笔记-3507-移除最小数对使数组有序I
笔记·leetcode
程序员-King.8 小时前
day158—回溯—全排列(LeetCode-46)
算法·leetcode·深度优先·回溯·递归
菜鸟233号15 小时前
力扣213 打家劫舍II java实现
java·数据结构·算法·leetcode
狐5715 小时前
2026-01-18-LeetCode刷题笔记-1895-最大的幻方
笔记·算法·leetcode
Q741_14715 小时前
C++ 队列 宽度优先搜索 BFS 力扣 662. 二叉树最大宽度 每日一题
c++·算法·leetcode·bfs·宽度优先
踩坑记录16 小时前
leetcode hot100 54.螺旋矩阵 medium
leetcode
源代码•宸18 小时前
Leetcode—3. 无重复字符的最长子串【中等】
经验分享·后端·算法·leetcode·面试·golang·string
历程里程碑18 小时前
哈希2:字母异位符分组
算法·leetcode·职场和发展
Stardep19 小时前
算法入门20——二分查找算法——搜索插入位置
数据结构·算法·leetcode
老鼠只爱大米19 小时前
LeetCode经典算法面试题 #141:环形链表(快慢指针、标记节点等多种方法详细解析)
算法·leetcode·链表·快慢指针·floyd算法·环形链表