【題解】LeetCode 1306. Jump Game III

【題目敘述】https://leetcode.com/problems/jump-game-iii/

class Solution {
public:
    bool canReach(vector<int>& a, int start) {
        queue <int> q;
        int vis[50005] = {};
        if (a[start] == 0) return true;
        q.push(start);
        vis[start] = 1;
        while (!q.empty()){
            int now = q.front();
            q.pop();
            int nxt = now-a[now];
            if (nxt >= 0 && !vis[nxt]){
                if (a[nxt] == 0) return true;
                q.push(nxt);
                vis[nxt] = 1;
            }
            nxt = now+a[now];
            if (nxt < a.size() && !vis[nxt]){
                if (a[nxt] == 0) return true;
                q.push(nxt);
                vis[nxt] = 1;
            }
        }
        return false;
    }
};
分享本文 Share with friends