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 + 1 where: i + 1 < arr.length.
i - 1 where: i - 1 >= 0.
j where: arr[i] == arr[j] and i != 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.
Solution
Use BFS. First, we have to record the index of each value and use the queue to BFS and to see which ways we can explore, and also use dp array to store the result. At the end, you can return end.
// time:O(n) space:O(n) publicintminJumps(int[] arr){ if (arr == null || arr.length == 0) return0; int n = arr.length; int[] dp = newint[n];// the shortest path to dp[i]; Arrays.fill(dp, -1); HashMap<Integer, List<Integer>> indexOfValue = new HashMap<>(); for (int i = 0; i < n; i++) { indexOfValue.computeIfAbsent(arr[i], x -> new LinkedList<>()).add(i); } Queue<Integer> queue = new LinkedList<>(); dp[0] = 0; queue.offer(0); while (!queue.isEmpty()) { int curr = queue.poll(); List<Integer> next = indexOfValue.get(arr[curr]); // put the curr + 1, curr - 1 and we will validate in the following steps next.add(curr - 1); next.add(curr + 1); for (int index : next) { // dp[index] == -1 means we didn't visit yet if (index >= 0 && index < n && dp[index] == -1) { dp[index] = dp[curr] + 1; queue.offer(index); } } next.clear(); } return dp[n - 1]; }