-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathjump_game_3.cpp
More file actions
35 lines (27 loc) · 943 Bytes
/
jump_game_3.cpp
File metadata and controls
35 lines (27 loc) · 943 Bytes
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
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool canReach(vector<int>& nums, int startIndex) {
vector<int> visited(nums.size(), 0);
return explore(nums, startIndex, visited);
}
private:
bool explore(vector<int>& nums, int currentIndex, vector<int>& visited) {
if (currentIndex < 0 || currentIndex >= nums.size()) return false;
if (visited[currentIndex]) return false;
if (nums[currentIndex] == 0) return true;
visited[currentIndex] = 1;
return explore(nums, currentIndex + nums[currentIndex], visited) ||
explore(nums, currentIndex - nums[currentIndex], visited);
}
};
int main() {
Solution solution;
vector<int> nums = {4, 2, 3, 0, 3, 1, 2};
int startIndex = 5;
bool result = solution.canReach(nums, startIndex);
cout << (result ? "Reachable" : "Not Reachable") << endl;
return 0;
}