LeetCode 1345
Jump Game 系列4: 这个需要我们求最小的跳转次数,考虑了几种思路,一个是类似于dfs的方法,然后每次到达最后,我们记录需要几次跳转,然后求最小的出来。想到dfs之后,觉得因为是求最小跳转次数,那么用bfs更好,每次向目标前进一步,如果reach到目标,那么跳转的次数最少。可以从起点做,也可以从终点开始。
def minJumps(self, arr: List[int]) -> int:
cacheList = collections.defaultdict(set)
#先做一个cache,把相同value的位置都先计算好
for i, a in enumerate(arr):
if a not in cacheList:
cacheList[a] = set()
cacheList[a].add(i)
#BFS
queue = list()
visited = set()
queue.append((len(arr)-1, 0))
visited.add(len(arr)-1)
while queue:
cpos, clevel = queue.pop(0)
if cpos == 0:
return clevel
copy = cacheList[arr[cpos]].copy()
#可以从邻居的到自己
if 0 <= cpos -1 < len(arr):
copy.add(cpos-1)
if 0 <= cpos +1 < len(arr):
copy.add(cpos+1)
#去掉自己
copy.remove(cpos)
for npos in copy:
if npos not in visited:
queue.append((npos, clevel + 1))
visited.add(npos)
return -1