-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathJump Game IV.java
More file actions
39 lines (39 loc) · 1.34 KB
/
Jump Game IV.java
File metadata and controls
39 lines (39 loc) · 1.34 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
class Solution {
public int minJumps(int[] arr) {
int n = arr.length;
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
graph.computeIfAbsent(arr[i], k -> new ArrayList<>()).add(i);
}
Queue<Integer> path = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
path.add(0);
int steps = 0;
while (!path.isEmpty()) {
int size = path.size();
while (size-- > 0) {
int removed = path.remove();
if (removed == n - 1) {
return steps;
}
for (Integer child : graph.get(arr[removed])) {
if (!visited.contains(child)) {
visited.add(child);
path.add(child);
}
}
graph.get(arr[removed]).clear();
if (removed + 1 < n && !visited.contains(removed + 1)) {
visited.add(removed + 1);
path.add(removed + 1);
}
if (removed - 1 >= 0 && !visited.contains(removed - 1)) {
visited.add(removed - 1);
path.add(removed - 1);
}
}
steps++;
}
return -1;
}
}