hwooo
LeetCode (C/C++) 1306. Jump Game III 본문
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;
}
};
'Study > Algorithm' 카테고리의 다른 글
| LeetCode (C/C++) 565. Array Nesting (0) | 2024.11.28 |
|---|---|
| 프로그래머스 (C/C++) 42888 : 오픈채팅방 (0) | 2024.11.28 |
| LeetCode (C/C++) 313. Super Ugly Number (0) | 2024.11.26 |
| 프로그래머스 (C/C++) 86971 : 전력망을 둘로 나누기 (0) | 2024.11.25 |
| LeetCode (C/C++) 34. Find First and Last Position of Element in Sorted Array (0) | 2024.11.22 |