-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathfrog-jump.py
41 lines (30 loc) · 1.27 KB
/
frog-jump.py
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
40
41
from functools import cache
from typing import List, Set
class Solution:
def canCross(self, stones: List[int]) -> bool:
dp: List[Set[int]] = [set() for _ in stones]
dp[0].add(0)
stone_pos = {stone: pos for pos, stone in enumerate(stones)}
for stone in range(len(stones)):
for jump in dp[stone]:
for next_jump in filter(lambda j: j > 0, (jump - 1, jump, jump + 1)):
next_stone = stones[stone] + next_jump
if next_stone in stone_pos:
dp[stone_pos[next_stone]].add(next_jump)
if dp[-1]:
return True
return False
def canCrossRecursive(self, stones: List[int]) -> bool:
stone_pos = {stone: pos for pos, stone in enumerate(stones)}
@cache
def dfs(stone: int, jump: int) -> bool:
if stone + 1 == len(stones):
return True
for next_jump in (jump - 1, jump, jump + 1):
if next_jump > 0:
next_stone = stones[stone] + next_jump
if next_stone in stone_pos:
if dfs(stone_pos[next_stone], next_jump):
return True
return False
return dfs(0, 0)