Skip to content

Commit 7d27cb0

Browse files
committed
LC 1306
1 parent 4cac86d commit 7d27cb0

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def canReach(self, arr: List[int], start: int) -> bool:
6+
visited = set()
7+
8+
def dfs(idx):
9+
if idx in visited:
10+
return False
11+
if arr[idx] == 0:
12+
return True
13+
visited.add(idx)
14+
jump = arr[idx]
15+
hi, lo = idx+jump, idx-jump
16+
res = dfs(hi) if hi < len(arr) else False
17+
res |= dfs(lo) if 0 <= lo else False
18+
return res
19+
20+
return dfs(start)
21+
22+
23+
s = Solution()
24+
cases = [
25+
([4, 2, 3, 0, 3, 1, 2], 5, True),
26+
([4, 2, 3, 0, 3, 1, 2], 0, True),
27+
([3, 0, 2, 1, 2], 2, False),
28+
]
29+
for arr, start, expected in cases:
30+
actual = s.canReach(arr, start)
31+
assert actual == expected, f"{arr, start}: {expected} != {actual}"

0 commit comments

Comments
 (0)