1345. 跳跃游戏 IV

class Solution {
public:
    int minJumps(vector<int>& arr) {
        int n=arr.size();
        unordered_map<int,vector<int>>idxSameValue;
        for(int i=0;i<n;++i)
            idxSameValue[arr[i]].emplace_back(i);
        unordered_set<int>visitedIndex;
        queue<pair<int,int>>q;
        q.emplace(0,0);
        visitedIndex.emplace(0);
        while(!q.empty()){
            auto[idx, step]=q.front();
            q.pop();
            if(idx==n-1) return step;
            step++;
            // 等值查找
            int v=arr[idx];
            if(idxSameValue.count(v)){
                for(int &i:idxSameValue[v]){
                    if(!visitedIndex.count(i)){
                        q.emplace(i,step);
                        visitedIndex.emplace(i);
                    }
                }
                idxSameValue.erase(v);
            }
            // 往后查找
            if(idx+1<n && !visitedIndex.count(idx+1)){
                q.emplace(idx+1,step);
                visitedIndex.emplace(idx+1);
            }
            // 往前查找
            if(idx-1>=0 && !visitedIndex.count(idx-1)){
                q.emplace(idx-1,step);
                visitedIndex.emplace(idx-1);
            }
        }
        return -1;
    }
};

你可能感兴趣的:(LeetCode,游戏,算法)