DeepRest

Jump Game IV

Jan 15th, 2022 (edited)
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. class Solution(object):
  2.     def minJumps(self, arr):
  3.         """
  4.        :type arr: List[int]
  5.        :rtype: int
  6.        """
  7.         n = len(arr)
  8.         hm = {}
  9.         for i, e in enumerate(arr):
  10.             hm.setdefault(e, []).append(i)
  11.        
  12.         #bfs
  13.         vis = set([-1,0])
  14.         dq = deque([(0, 0)])
  15.         while dq:
  16.             cn, cd = dq.pop()
  17.            
  18.             if cn == n-1:
  19.                 return cd
  20.            
  21.             if cn-1 not in vis:
  22.                 vis.add(cn-1)
  23.                 dq.appendleft((cn-1, cd+1))
  24.                
  25.             if cn+1 not in vis:
  26.                 vis.add(cn+1)
  27.                 dq.appendleft((cn+1, cd+1))
  28.            
  29.             for i in hm[arr[cn]]:
  30.                 if i not in vis:
  31.                     vis.add(i)
  32.                     dq.appendleft((i, cd+1))
  33. '''since all indices with value arr[cn] has been added to the que, we erase the hash value for arr[cn] so for all these indices added to the queue the for loop is not executed(as it will never satisfy unvisited condition anyways, if not erased)'''
  34.             hm[arr[cn]] = [] #imp to avoid tle... equivalent classes
  35.            
  36.         return -1
  37.            
Add Comment
Please, Sign In to add comment