Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #iterative version
- class Solution(object):
- def canReach(self, arr, start):
- """
- :type arr: List[int]
- :type start: int
- :rtype: bool
- """
- dq = deque([start])
- while dq:
- #for dfs
- curr = dq.pop()
- #for bfs
- #curr = dq.popleft()
- #1&2 conditions can be checked either when the position is seen (i.e added to dq) or when its processed (i.e removed from dq)
- if not 0 <= curr < len(arr) or arr[curr] < 0:#1
- continue
- if arr[curr] == 0:#2, no further jumps, as 0 is additive n subtractive identity
- return True
- # -ve sign used as insitu visited marker; also, a+b = a-(-b) and a-b = a+(-b)
- arr[curr] *= -1
- dq.append(curr + arr[curr])
- dq.append(curr - arr[curr])
- return False
- #recursive version
- '''
- class Solution(object):
- def canReach(self, arr, start):
- """
- :type arr: List[int]
- :type start: int
- :rtype: bool
- """
- if not 0<=start<len(arr) or arr[start] < 0:
- return False
- arr[start] *= -1
- # due to SHORT CIRCUIT(LAZY) EVALUATION sub expressions following true subexp. are not evaluated.
- return arr[start] == 0 or self.canReach(arr, start-arr[start]) or self.canReach(arr, start+arr[start])
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement