# Check if it is possible to reach a number by making jumps of two given length in Python

PythonServer Side ProgrammingProgramming

Suppose we are at starting position p, we can jump at any direction (left or right) d1 and d2 units. We have to find minimum number of steps required to reach at position q by jumping from p.

So, if the input is like p = 5, q = 10, d1 = 4, d2 = 3, then the output will be 3 as we can jump to right using distance 4 twice then we can reach at location 13, then jump left 3 units to reach 10.

To solve this, we will follow these steps −

• gcd_res := gcd of d1 and d2
• if (p - q) is not divisible by gcd_res, then
• return -1
• que := define one double ended queue
• visited := a new set
• insert a pair (p, 0) into queue
• mark p as visited
• while size of que > 0 is non-zero, do
• (point, step) := front element of queue and delete it from que
• if point is same as q, then
• return step
• if point + d1 is not visited, then
• insert a pair (point + d1, step + 1) into que
• mark (point + d1) as visited
• if point + d2 not in visited is non-zero, then
• insert a pair (point + d2, step + 1) into que
• mark (point + d2) as visited
• if point - d1 not in visited is non-zero, then
• insert a pair (point - d1, step + 1) into que
• mark (point - d1) as visited
• if point - d2 not in visited is non-zero, then
• insert a pair (point - d2, step + 1) into que
• mark (point - d2) as visited

## Example

Let us see the following implementation to get better understanding −

from math import gcd
from collections import deque
def solve(p, d1, d2, q):
gcd_res = gcd(d1, d2)
if (p - q) % gcd_res != 0:
return -1
que = deque()
visited = set()
que.appendleft([p, 0])
while len(que) > 0:
pair = que.pop()
point, step = pair[0], pair[1]
if point == q:
return step
if point + d1 not in visited:
que.appendleft([(point + d1), step + 1])
if point + d2 not in visited:
que.appendleft([(point + d2), step + 1])
if point - d1 not in visited:
que.appendleft([(point - d1), step + 1])
if point - d2 not in visited:
que.appendleft([(point - d2), step + 1])
p = 5
q = 10
d1 = 4
d2 = 3
print(solve(p, d1, d2, q))

## Input

5, 4, 3, 10

## Output

True
Published on 18-Jan-2021 13:20:25