Skip to content

Commit 239acb4

Browse files
authored
Create jump-game-iii.cpp
1 parent ef9fb79 commit 239acb4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

C++/jump-game-iii.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
bool canReach(vector<int>& arr, int start) {
7+
queue<int> q({start});
8+
unordered_set<int> lookup = {start};
9+
while (!q.empty()) {
10+
const auto i = q.front(); q.pop();
11+
if (!arr[i]) {
12+
return true;
13+
}
14+
for (const auto& j : {i - arr[i], i + arr[i]}) {
15+
if (0 <= j && j < arr.size() && !lookup.count(j)) {
16+
lookup.emplace(j);
17+
q.emplace(j);
18+
}
19+
}
20+
}
21+
return false;
22+
}
23+
};

0 commit comments

Comments
 (0)