-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
canReach.cpp
34 lines (25 loc) · 949 Bytes
/
canReach.cpp
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
class Solution {
private:
bool canReachHelper(vector<int>& arr, int start, unordered_map<int, bool>& dp, unordered_set<int>& inStack) {
if(start < 0 || start >= arr.size())
return false;
if(arr[start] == 0)
return true;
if(inStack.count(start) > 0)
return false;
if(dp.count(start) > 0)
return dp[start];
inStack.insert(start);
bool left = canReachHelper(arr, start - arr[start], dp, inStack);
bool right = left || canReachHelper(arr, start + arr[start], dp, inStack);
dp[start] = left || right;
inStack.erase(start);
return dp[start];
}
public:
bool canReach(vector<int>& arr, int start) {
unordered_map<int, bool> dp;
unordered_set<int> inStack;
return canReachHelper(arr, start, dp, inStack);
}
};