Input: arr =[100,-23,-23,404,100,23,23,23,3,404]Output: 3Explanation: You need three jumps from index 0-->4-->3-->9. Note that index 9is the last index of the array.
Example 2:
1
2
3
Input: arr =[7]Output: 0Explanation: Start index is the last index. You do not need to jump.
Example 3:
1
2
3
Input: arr =[7,6,9,6,9,6,9,7]Output: 1Explanation: You can jump directly from index 0 to index 7 which is last index of the array.
The shortest path in an unweighted graph can be found using BFS. Here, each index is a node, and you can jump to adjacent indices or any index with the same value. BFS ensures we find the minimum steps to reach the last index.
classSolution {
public:int minJumps(vector<int>& arr) {
int n = arr.size();
if (n ==1) return0;
unordered_map<int, vector<int>> m;
for (int i =0; i < n; ++i) m[arr[i]].push_back(i);
queue<int> q;
vector<bool> vis(n, false);
q.push(0);
vis[0] = true;
int ans =0;
while (!q.empty()) {
int sz = q.size();
while (sz--) {
int i = q.front(); q.pop();
if (i == n -1) return ans;
vector<int>& nxt = m[arr[i]];
nxt.push_back(i -1);
nxt.push_back(i +1);
for (int j : nxt) {
if (j >=0&& j < n &&!vis[j]) {
vis[j] = true;
q.push(j);
}
}
m[arr[i]].clear();
}
++ans;
}
return-1;
}
}
classSolution {
publicintminJumps(int[] arr) {
int n = arr.length;
if (n == 1) return 0;
Map<Integer, List<Integer>> m =new HashMap<>();
for (int i = 0; i < n; i++) m.computeIfAbsent(arr[i], k ->new ArrayList<>()).add(i);
Queue<Integer> q =new LinkedList<>();
boolean[] vis =newboolean[n];
q.offer(0);
vis[0]=true;
int ans = 0;
while (!q.isEmpty()) {
int sz = q.size();
for (int k = 0; k < sz; k++) {
int i = q.poll();
if (i == n - 1) return ans;
List<Integer> nxt = m.get(arr[i]);
nxt.add(i - 1);
nxt.add(i + 1);
for (int j : nxt) {
if (j >= 0 && j < n &&!vis[j]) {
vis[j]=true;
q.offer(j);
}
}
nxt.clear();
}
ans++;
}
return-1;
}
}
classSolution {
funminJumps(arr: IntArray): Int {
val n = arr.size
if (n ==1) return0val m = mutableMapOf<Int, MutableList<Int>>()
for (i in arr.indices) m.getOrPut(arr[i]) { mutableListOf() }.add(i)
val vis = BooleanArray(n)
val q: ArrayDeque<Int> = ArrayDeque()
q.add(0)
vis[0] = truevar ans = 0while (q.isNotEmpty()) {
repeat(q.size) {
val i = q.removeFirst()
if (i == n - 1) return ans
val nxt = m[arr[i]]!! nxt.add(i - 1)
nxt.add(i + 1)
for (j in nxt) {
if (j in0 until n && !vis[j]) {
vis[j] = true q.add(j)
}
}
nxt.clear()
}
ans++ }
return -1 }
}
classSolution:
defminJumps(self, arr: list[int]) -> int:
n = len(arr)
if n ==1:
return0 m: dict[int, list[int]] = {}
for i, v in enumerate(arr):
m.setdefault(v, []).append(i)
vis = [False] * n
q = [0]
vis[0] =True ans =0while q:
nq = []
for i in q:
if i == n -1:
return ans
for j in m[arr[i]] + [i -1, i +1]:
if0<= j < n andnot vis[j]:
vis[j] =True nq.append(j)
m[arr[i]].clear()
q = nq
ans +=1return-1