Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution(object):
- def minJumps(self, arr):
- """
- :type arr: List[int]
- :rtype: int
- """
- n = len(arr)
- hm = {}
- for i, e in enumerate(arr):
- hm.setdefault(e, []).append(i)
- #bfs
- vis = set([-1,0])
- dq = deque([(0, 0)])
- while dq:
- cn, cd = dq.pop()
- if cn == n-1:
- return cd
- if cn-1 not in vis:
- vis.add(cn-1)
- dq.appendleft((cn-1, cd+1))
- if cn+1 not in vis:
- vis.add(cn+1)
- dq.appendleft((cn+1, cd+1))
- for i in hm[arr[cn]]:
- if i not in vis:
- vis.add(i)
- dq.appendleft((i, cd+1))
- '''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)'''
- hm[arr[cn]] = [] #imp to avoid tle... equivalent classes
- return -1
Add Comment
Please, Sign In to add comment