// 演算法 / Algorithm:
// 同 C 版本：BFS 從 start 出發，每個索引最多訪問一次，
// 用 std::queue<int> 管理待處理索引，原地把 arr[i] 取負作為已訪問旗標。
// Same as the C version: BFS from start, each index visited at most once,
// using std::queue<int> as the worklist and in-place negation of arr[i] as the visited flag.

#include <vector>      // std::vector
#include <queue>       // std::queue
#include <cstdlib>     // std::abs

class Solution {
public:
    bool canReach(std::vector<int>& arr, int start) {
        const int n = arr.size();         // 取得陣列大小 / cache the array size
        if (arr[start] == 0) return true; // 起點就是 0 直接成功 / start itself is a zero

        std::queue<int> q;                // BFS 用的 queue（先進先出）/ FIFO worklist for BFS
        q.push(start);                    // 入隊起點 / enqueue the start
        arr[start] = -arr[start];         // 標記已訪問（取負）/ mark visited by negation

        while (!q.empty()) {              // 還有待處理索引就繼續 / loop until queue drains
            int i = q.front();            // 取隊首 / peek front
            q.pop();                      // 移除隊首 / remove front
            int step = -arr[i];           // 還原原始跳躍距離 / recover original jump distance

            // lambda：嘗試訪問鄰居 j。若 j 是 0 回傳 true；若可訪問則標記並入隊。
            // Lambda: try visiting neighbor j. Returns true if j is a zero (success).
            // Captures by reference so it can read/modify arr and q.
            auto visit = [&](int j) -> bool {
                if (j < 0 || j >= n) return false;   // 出界 / out of bounds
                if (arr[j] == 0) return true;        // 找到 0 / hit a zero
                if (arr[j] > 0) {                    // 還沒訪問過 / unvisited
                    arr[j] = -arr[j];                // 標記 / mark visited
                    q.push(j);                       // 入隊 / enqueue
                }
                return false;                        // 還沒找到 0 / not a success yet
            };

            if (visit(i + step)) return true;        // 試右跳 / try right jump
            if (visit(i - step)) return true;        // 試左跳 / try left jump
        }

        return false;                                // queue 空了還沒找到 / no zero reachable
    }
};
