topic
https://leetcode-cn.com/problems/jump-game-iii/
There is an array of non-negative integers, arr, and you are at the beginning of the array. When you are at the subscript i, you can jump to i + arr [i] or i-arr [i].
Please judge whether you can jump to any subscript where the corresponding element value is 0.
Note that no matter what the situation, you cannot jump outside the array.
Example 1:
Input: arr = [4,2,3,0,3,1,2], start = 5
Output: true
Explanation:
Subscript 3 with a value of 0 has the following possible solutions:
subscript 5-> subscript 4-> subscript 1-> subscript 3
subscript 5-> subscript 6-> subscript 4-> subscript 1-> subscript 3
Example 2:
Input: arr = [4,2,3,0,3,1,2], start = 0
Output: true
Explanation:
Subscript 3 with a value of 0 has the following possible solutions:
subscript 0-> subscript 4-> subscript 1-> subscript 3
Example 3:
Input: arr = [3,0,2,1,2], start = 2
Output: false
Explanation: Subscript 1 with a value of 0 cannot be reached.
prompt:
1 <= arr.length <= 5 * 10^4
0 <= arr[i] < arr.length
0 <= start < arr.length
Problem-solving ideas
- Standard BFS process
- Use
seen_set
set storage to access subscripts - When traversing the breadth, in addition to judging whether it has been visited, it is also necessary to check whether it has crossed the left and right borders
Code
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
seen_set = set([start])
q = [start]
while q:
p = q.pop(0)
if arr[p] == 0:
return True
for k in [p-arr[p], p+arr[p]]:
if k in seen_set: continue
if 0 <= k <= len(arr)-1:
q.append(k)
seen_set.add(k)
return False