92. Can you reach the end?
You stand on the first square of a row of squares. The number on each square is the longest jump you may make from it: from a square marked 3 you may move forward 1, 2 or 3 squares. A square marked 0 lets you go no further from there.
Write a function can_reach_end(jumps) that takes the list of numbers and returns True if you can reach the last
square, or False if you can't.
- With a single square you are already at the end:
True. - Jumping as far as possible every time isn't always right: in
[2, 5, 0, 0]the longest first jump lands on a 0, but a jump of 1 reaches the 5, which goes all the way. - Landing beyond the last square counts as reaching it.
Example 1
jumps = [1, 2, 0, 1]TrueExample 2
jumps = [2, 1, 0, 3]FalseExample 3
jumps = [0]TrueConstraints
jumpshas 1 to 500 whole numbers, each from 0 to 1000.
Submit also runs 9 more tests you can't see.
- You don't need to try every route. Keep the farthest square you know you can reach so far, starting at 0.
- Walk along the squares in order. From square
iyou can reach as far asi + jumps[i], so the farthest point may move further. - If you come to a square beyond the farthest reachable one, you are stuck: return
False. If the walk gets through every square, the end is reachable.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def can_reach_end(jumps):
"""Check whether the last square can be reached.
jumps: list of int, the longest jump from each square
Returns: bool, True if some series of jumps from the
first square reaches the last
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.