Advertisement
DeepRest

Jump Game III

Dec 9th, 2021 (edited)
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. #iterative version
  2. class Solution(object):
  3.     def canReach(self, arr, start):
  4.         """
  5.        :type arr: List[int]
  6.        :type start: int
  7.        :rtype: bool
  8.        """
  9.         dq = deque([start])
  10.        
  11.         while dq:
  12.             #for dfs
  13.             curr = dq.pop()
  14.            
  15.             #for bfs
  16.             #curr = dq.popleft()
  17.  
  18.             #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)
  19.             if not 0 <= curr < len(arr) or arr[curr] < 0:#1
  20.                 continue
  21.                
  22.             if arr[curr] == 0:#2, no further jumps, as 0 is additive n subtractive identity
  23.                 return True
  24.            
  25.             # -ve sign used as insitu visited marker; also, a+b = a-(-b) and a-b = a+(-b)
  26.             arr[curr] *= -1
  27.            
  28.             dq.append(curr + arr[curr])
  29.             dq.append(curr - arr[curr])
  30.            
  31.         return False
  32.  
  33. #recursive version
  34. '''
  35. class Solution(object):
  36.    def canReach(self, arr, start):
  37.        """
  38.        :type arr: List[int]
  39.        :type start: int
  40.        :rtype: bool
  41.        """
  42.        if not 0<=start<len(arr) or arr[start] < 0:
  43.            return False
  44.        
  45.        arr[start] *= -1
  46.        
  47.        # due to SHORT CIRCUIT(LAZY) EVALUATION sub expressions following true subexp. are not evaluated.
  48.        return arr[start] == 0 or self.canReach(arr, start-arr[start]) or self.canReach(arr, start+arr[start])
  49. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement