通过在Python中进行两个给定长度的跳转来检查是否有可能达到一个数字
假设我们在起始位置p,我们可以在d1和d2单位的任意方向(左或右)上跳跃。我们必须找到从p跳转到位置q所需的最小步数。
因此,如果输入像p=5,q=10,d1=4,d2=3,那么输出将是3,因为我们可以使用距离4两次向右跳转,然后可以到达位置13,然后向左跳转3个单位即可达到10个。
示例
让我们看下面的实现以更好地理解-
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])
visited.add(p)
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])
visited.add(point + d1)
if point + d2 not in visited:
que.appendleft([(point + d2), step + 1])
visited.add(point + d2)
if point - d1 not in visited:
que.appendleft([(point - d1), step + 1])
visited.add(point - d1)
if point - d2 not in visited:
que.appendleft([(point - d2), step + 1])
visited.add(point - d2)
p = 5
q = 10
d1 = 4
d2 = 3
print(solve(p, d1, d2, q))输入值
5, 4, 3, 10输出结果
True
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短