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 class Solution { public int minimumJumps (int [] forbidden, int a, int b, int x) { Set<Integer> blackSet = new HashSet <>(); for (int f : forbidden) { blackSet.add(f); } int jumps = 0 ; Queue<Integer> queue = new LinkedList <>(); int [] visited = new int [6000 ]; queue.offer(0 ); visited[0 ] = 1 ; while (!queue.isEmpty()) { for (int i = queue.size(); i > 0 ; i--) { int position = queue.poll(); if (position == x) { return jumps; } int front = position + a; int back = position - b; if (front < visited.length && !blackSet.contains(front) && visited[front] <= 0 ) { queue.offer(front); visited[front] = 1 ; } if (visited[position] != -1 && back >= 0 && !blackSet.contains(back) && visited[back] == 0 ) { queue.offer(back); visited[back] = -1 ; } } jumps++; } return -1 ; } }
References 1654. Minimum Jumps to Reach Home