Posted on

Description

Submission

class Solution {
    vector<int> visited;
    int n;

    bool dfs(int cur, vector<int>& nums, int coeff) {
        if(coeff * nums[cur] < 0) return false;
        if(visited[cur] == 2) return false;
        if(visited[cur] == 1) return true;

        visited[cur] = 1;
        int next = (nums[cur] + cur + n * 10000) % n;

        bool ret;
        if(next == cur) ret = false;
        else ret = dfs(next, nums, coeff);
        visited[cur] = 2;

        return ret;
    }
public:
    bool circularArrayLoop(vector<int>& nums) {
        n = nums.size();

        visited.resize(n, 0);

        for(int i = 0; i < n; ++i) {
            if(dfs(i, nums, nums[i] / abs(nums[i]))) return true;
        }

        return false;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *