Minimum Jumps to Reach Home LeetCode solution in Java

1
class Solution {
2
public int minimumJumps(int[] forbidden, int a, int b, int x) {
3

4
// Visited Set
5
Set<Integer> visited = new HashSet<Integer>();
6

7
// Add forbidden coordinates to visited
8
for (int i = 0; i < forbidden.length; i++) {
9
visited.add(forbidden[i]);
10
}
11

12
// Distance/ Jumps map
13
Map<Integer, Integer> jumps = new HashMap<>();
14
jumps.put(0, 0);
15

16
// BFS Queue
17
Queue<Integer[]> q = new LinkedList<>();
18
q.add(new Integer[] {0, 1});
19

20
// BFS
21
while (q.size() != 0) {
22

23
Integer[] ud = q.poll();
24

25
int u = ud[0], d = ud[1];
26

27
// x found
28
if (u == x) {
29
return jumps.get(u);
30
}
31

32
// jump right
33
if (u + a < 6001 && !visited.contains(u + a)) {
34
q.add(new Integer[] {u + a, 1});
35
visited.add(u + a);
36
jumps.put(u + a, jumps.get(u) + 1);
37
}
38

39
// jump left
40
if (d != -1 && u - b > -1 && !visited.contains(u - b)) {
41
q.add(new Integer[] {u - b, -1});
42
jumps.put(u - b, jumps.get(u) + 1);
43
}
44
}
45

46
return -1;
47
}
48
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0