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;
    }
};
相关推荐
dying_man6 小时前
LeetCode--24.两两交换链表中的结点
算法·leetcode
yours_Gabriel6 小时前
【力扣】2434.使用机器人打印字典序最小的字符串
算法·leetcode·贪心算法
GGBondlctrl7 小时前
【leetcode】递归,回溯思想 + 巧妙解法-解决“N皇后”,以及“解数独”题目
算法·leetcode·n皇后·有效的数独·解数独·映射思想·数学思想
枫景Maple18 小时前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
緈福的街口21 小时前
【leetcode】3. 无重复字符的最长子串
算法·leetcode·职场和发展
小刘不想改BUG1 天前
LeetCode 70 爬楼梯(Java)
java·算法·leetcode
sz66cm1 天前
LeetCode刷题 -- 542. 01矩阵 基于 DFS 更新优化的多源最短路径实现
leetcode·矩阵·深度优先
爱coding的橙子1 天前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode