[LeetCode] Frog Jump

403. Frog Jump

A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of stones’ positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.

If the frog’s last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.

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
class Solution {
unordered_set<long> st;
unordered_map<string, bool> dp;
int goal;
string makeKey(int f, int u) {
return to_string(f) + '#' + to_string(u);
}
bool jump(long frog, long unit) {
if(frog == goal) return true;
string key = makeKey(frog, unit);
if(dp.count(key)) return dp[key];
bool res = false;
for(int i = max(1l, unit-1); i <= unit + 1 and !res; i++) {
if(st.count(frog + i)) res |= jump(frog + i, i);
}
return dp[key] = res;
}
public:
bool canCross(vector<int>& stones) {
if(stones[0] + 1 != stones[1]) return false;
goal = stones.back();
st.insert(stones.begin(), stones.end());
return jump(stones[1],1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/16/PS/LeetCode/frog-jump/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.