Program to find minimum jumps to reach home in Python

PythonServer Side ProgrammingProgramming

Suppose there is an array called forbidden, where forbidden[i] indicates that the bug cannot jump to the position forbidden[i], and we also have three values a, b, and x. A bug's home is at position x on the number line. It is at position 0 initially. it can jump by following rules −

  • Bug can jump exactly a positions to the right.

  • Bug can jump exactly b positions to the left.

  • Bug cannot jump backward twice in a row.

  • Bug cannot jump to any forbidden positions given in the array.

  • Bug can jump forward beyond its home, but it cannot jump to positions numbered with negative values.

We have to find the minimum number of jumps required for the bug to reach the destination. If there is no such possible sequence, then return -1.

So, if the input is like forbidden = [2,3,7,9, 12], a = 4, b = 2, x = 16, then the output will be 7 because, starting from 0, jump a = 4 forward twice to reach 4 and 8, but cannot jump to 12 as this is forbidden, then step back b = 2 at 6, then jump to 10, 14, 18 and then two back to reach 16, so there are 7 steps.

To solve this, we will follow these steps −

  • queue := a queue with a tuple (x,0,True), forbidden := a new set and insert elements from forbidden list

  • lim := a + b + (maximum of x and maximum value of forbidden set)

  • while queue is not empty, do

    • (curr,jumps,is_b) := first element from queue and remove it from queue

    • if curr is in forbidden or (0 <= curr <= lim) is false, then

      • go for next iteration

    • insert curr into forbidden

    • if curr is same as 0, then

      • return jumps

    • if is_b is true, then

      • insert (curr+b,jumps+1,False) into queue

    • insert (curr-a,jumps+1,True) into queue

  • return -1


Let us see the following implementation to get better understanding −

def solve(forbidden, a, b, x):
   queue, forbidden = [(x,0,True)], set(forbidden)
   lim = max(max(forbidden),x)+a+b
   while queue:
      curr,jumps,is_b = queue.pop(0)
      if curr in forbidden or not 0 <= curr <= lim:
      if curr==0:
         return jumps
      if is_b:
   return -1

forbidden = [2,3,7,9, 12]
a = 4
b = 2
x = 16
print(solve(forbidden, a, b, x))


[2,3,7,9, 12], 4, 2, 16


Published on 06-Oct-2021 07:36:01