Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

hwooo

LeetCode (C/C++) 1306. Jump Game III 본문

Study/Algorithm

LeetCode (C/C++) 1306. Jump Game III

hwooo 2024. 11. 27. 03:18

https://leetcode.com/problems/jump-game-iii/


풀이

현재 인덱스를 큐에 저장하며 탐색한다.

다음 인덱스를 탐색할 때는 배열의 범위인지, 이미 방문한 지점인지 확인하고 처음 방문한 지점일 때 큐에 삽입하여 탐색한다.


코드

class Solution {
public:
    bool visited[50000];
    bool canReach(vector<int>& arr, int start) {
        queue<int> q;

        q.push(start);
        visited[start] = true;

        while (!q.empty()) {
            int now = q.front();
            q.pop();

            // 현재 인덱스의 값이 0일 때
            if (arr[now] == 0)
                return true;

            // 다음 인덱스로 이동
            int next = now + arr[now];
            if (next < arr.size() && !visited[next]) {
                visited[next] = true;
                q.push(next);
            }

            next = now - arr[now];
            if (0 <= next && !visited[next]) {
                visited[next] = true;
                q.push(next);
            }
        }
        return false;
    }
};