
方法:建图,bfs求到arr末尾数字的最短路径
- 根据题目描述,我们可以把给定数组整理成一个无向图,数组中相邻的元素或者元素值相同的元素相连即可。
- 这就等价于求从arr[0]~arr[n-1]最短路径长度,容易想到BFS

class Solution {
public int minJumps(int[] arr) {
Map<Integer, List<Integer>> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
List<Integer> list = map.getOrDefault(arr[i], new ArrayList<>());
list.add(i);
map.put(arr[i], list);
}
Queue<Integer> queue = new LinkedList<>();
queue.offer(0);
boolean[] visited = new boolean[arr.length];
int step = 0;
while (!queue.isEmpty()) {
step++;
int size = queue.size();
for (int i = 0; i < size; i++) {
int idx = queue.poll();
if (idx == arr.length - 1) {
return step - 1;
}
if (map.containsKey(arr[idx])) {
for (int x : map.get(arr[idx])) {
if (!visited[x]) {
queue.offer(x);
visited[x] = true;
}
}
map.remove(arr[idx]);
}
if (idx - 1 >= 0 && !visited[idx - 1]) {
queue.offer(idx - 1);
visited[idx - 1] = true;
}
if (idx + 1 < arr.length && !visited[idx + 1]) {
queue.offer(idx + 1);
visited[idx + 1] = true;
}
}
}
return step;
}
}