我试图解决一个国王移动(国际象棋)任务。我发现国王只有在它的坐标-1 <= x1-x2 and y1-y2 <= 1
时才会移动。
我的代码是:
x1 = int(input()) #cuurent x-position
y1 = int(input()) #current y-position
x2 = int(input()) #estimated x-position
y2 = int(input()) #estimated y-position
if -1 <= x1-x2 and y1-y2 <= 1: #king can move to the x2-y2 from x1-y1
print('YES')
else: #king can't move to the x2-y2 from x1-y1
print('NO')
我能找到的所有'YES'动作都能很好地工作,但它不能用于某些'NO'动作,例如:
x1 = 4,y1 = 4,x2 = 2,y2 = 6或x1 = 4,y1 = 4,x2 = 4,y2 = 6
。我不明白为什么,因为:4-4 = 0,但4-6 = -2,-2小于-1。
答案 0 :(得分:4)
如果坐标之间的绝对差异小于或等于1,则国王可以移动。
所以,写:
if abs(x1-x2) <= 1 and abs(y1-y2) <= 1: #king can move to the x2-y2 from x1-y1
print('YES')
else: #king can't move to the x2-y2 from x1-y1
print('NO')
这是因为您正在移动的坐标可能比您要移动的坐标更大/更小,但是您知道它们最多相差1个。