Jump Game IV
Given an array of integers arr, you are initially positioned at the first index of the array.
In one step you can jump from index i to index:
i + 1where:i + 1 < arr.length.i - 1where:i - 1 >= 0.jwhere:arr[i] == arr[j]andi != j.
Return the minimum number of steps to reach the last index of the array.
Notice that you can not jump outside of the array at any time.
Example 1:
Input: arr = [100,-23,-23,404,100,23,23,23,3,404] Output: 3 Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
Example 2:
Input: arr = [7] Output: 0 Explanation: Start index is the last index. You do not need to jump.
Example 3:
Input: arr = [7,6,9,6,9,6,9,7] Output: 1 Explanation: You can jump directly from index 0 to index 7 which is last index of the array.
Constraints:
1 <= arr.length <= 5 * 104-10^8 <= arr[i] <= 10^8
题解
下次看到一维数组的最少步数寻路问题基本都用BFS
求解步骤
- 建立一个num_dic,存储 值:下标集合 的映射关系,建立队列q。
- 用BFS,每一步,判断当前的坐标cur_pos是否为arr.size()-1:
- 如果是,返回当前的坐标
- 否则,将cur_pos+1、cur_pos-1、num_dic[cur_pos]中的每一个坐标都加入q中。继续下一个
- 注意要vis。
代码
MAX=5*10**4+5
class Solution:
def minJumps(self, arr: List[int]) -> int:
n=len(arr)
min_step=[MAX for i in range(n)]
num_dic={}
for i in range(n):
if arr[i] in num_dic:
num_dic[arr[i]].append(i)
else:
num_dic[arr[i]]=[i]
q=deque()
q.append([0,0])
vis=[False for i in range(n)]
while len(q)>0:
if q[0][0]==n-1:
return q[0][1]
cur_pos,cur_ct=q.popleft()
vis[cur_pos]=True
if cur_pos+1<n and vis[cur_pos+1]==False:
q.append([cur_pos+1,cur_ct+1])
if cur_pos-1>=0 and vis[cur_pos-1]==False:
q.append([cur_pos-1,cur_ct+1])
for j in num_dic[arr[cur_pos]]:
if vis[j]==False:
q.append([j,cur_ct+1])
num_dic[arr[cur_pos]]=[]
给定一个整数数组,从第一个索引开始,你可以按i+1、i-1或者到值相等的其他索引j跳跃。目标是到达数组的最后一个索引,返回达到目标所需的最小步数。文章提供了一个使用BFS并借助字典存储值与索引关系的Python解决方案。
774

被折叠的 条评论
为什么被折叠?



