forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path403.frog-jump.cpp
39 lines (31 loc) · 1.06 KB
/
403.frog-jump.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
35
36
37
38
39
class Solution {
public:
bool canCross(vector<int>& stones) {
if (stones.size() == 0){
return true;
}
// key = kth stone, available jump distances at kth stone
unordered_map<int, unordered_set<int>> map;
for(auto i = 0; i < stones.size(); ++i){
map[stones[i]] = unordered_set<int>();
}
map[stones[0]].insert(1);
for (auto i = 0; i< stones.size(); ++i){
int kth = stones[i];
for (int step: map[kth]){
int reach = step + kth;
if (reach == stones[stones.size() - 1]){
return true;
}
if (map.count(reach) > 0){
if (step - 1 > 0){
map[reach].insert(step - 1);
}
map[reach].insert(step);
map[reach].insert(step + 1);
}
}
}
return false;
}
};