|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/jump-game-iii/ |
| 3 | + |
| 4 | +Given an array of non-negative integers arr, you are initially positioned |
| 5 | +at start index of the array. When you are at index i, |
| 6 | +you can jump to i + arr[i] or i - arr[i], check if you can reach to |
| 7 | +any index with value 0. |
| 8 | +Notice that you can not jump outside of the array at any time. |
| 9 | + |
| 10 | +Example 1: |
| 11 | +Input: arr = [4,2,3,0,3,1,2], start = 5 |
| 12 | +Output: true |
| 13 | +Explanation: |
| 14 | +All possible ways to reach at index 3 with value 0 are: |
| 15 | +index 5 -> index 4 -> index 1 -> index 3 |
| 16 | +index 5 -> index 6 -> index 4 -> index 1 -> index 3 |
| 17 | + |
| 18 | +Example 2: |
| 19 | +Input: arr = [4,2,3,0,3,1,2], start = 0 |
| 20 | +Output: true |
| 21 | +Explanation: |
| 22 | +One possible way to reach at index 3 with value 0 is: |
| 23 | +index 0 -> index 4 -> index 1 -> index 3 |
| 24 | + |
| 25 | +Example 3: |
| 26 | +Input: arr = [3,0,2,1,2], start = 2 |
| 27 | +Output: false |
| 28 | +Explanation: There is no way to reach at index 1 with value 0. |
| 29 | + |
| 30 | +Constraints: |
| 31 | +1 <= arr.length <= 5 * 104 |
| 32 | +0 <= arr[i] < arr.length |
| 33 | +0 <= start < arr.length |
| 34 | +""" |
| 35 | +class Solution: |
| 36 | + def canReach(self, arr: List[int], start: int) -> bool: |
| 37 | + return self.helper(start, arr, set()) |
| 38 | + |
| 39 | + def helper(self, index, arr, visited): |
| 40 | + if index < 0 or index >= len(arr) or index in visited: |
| 41 | + return False |
| 42 | + |
| 43 | + if arr[index] == 0: |
| 44 | + return True |
| 45 | + visited.add(index) |
| 46 | + |
| 47 | + return self.helper(index + arr[index], arr, visited) or self.helper(index - arr[index], arr, visited) |
0 commit comments