Repository navigation
Expand file tree
/
Copy path1345. Jump Game IV.java
More file actions
55 lines (43 loc) · 1.51 KB
/
Copy path1345. Jump Game IV.java
File metadata and controls
55 lines (43 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public int minJumps(int[] arr) {
int n = arr.length;
if (n <= 1) return 0;
Map<Integer, List<Integer>> portals = new HashMap<>();
for (int i = 0; i < n; i++) {
List<Integer> list = portals.getOrDefault(arr[i], new ArrayList<>());
list.add(i);
portals.put(arr[i], list);
}
Queue<Integer> queue = new LinkedList<>();
boolean[] visited = new boolean[n];
queue.offer(0);
visited[0] = true;
int steps = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int curr = queue.poll();
if (curr == n - 1) return steps;
if (curr + 1 < n && !visited[curr + 1]) {
visited[curr + 1] = true;
queue.offer(curr + 1);
}
if (curr - 1 >= 0 && !visited[curr - 1]) {
visited[curr - 1] = true;
queue.offer(curr - 1);
}
if (portals.containsKey(arr[curr])) {
for (int nextIdx : portals.get(arr[curr])) {
if (!visited[nextIdx]) {
visited[nextIdx] = true;
queue.offer(nextIdx);
}
}
portals.remove(arr[curr]);
}
}
steps++;
}
return -1;
}
}