首页 > 其他 > 详细

螺旋队列题解

时间:2019-12-12 11:24:31      阅读:64      评论:0      收藏:0      [点我收藏+]
"""
现有如下数列:
43 44 45 46 47 ......
42 21 22 23 24 25 26
41 20  7  8  9 10 27
40 19  6  1  2 11 28
39 18  5  4  3 12 29
38 17 16 15 14 13 30
37 36 35 34 33 32 31

看清楚以上数字排列的规律,设数字1位置的坐标为(0,0),x方向向右为正,y方向向下为正。
例如7的坐标为(-1,-1),2的坐标为(1,0),3的坐标为(1,1)。
编程实现输入任意坐标(x,y),输出对应的数字。
"""
import math

def get_num(x, y):
    result = 0


    if x == y == 0:
        result = 1
        return result


    if abs(x) < abs(y):
        temp = math.pow((2*abs(y)+1), 2)  # 本质是 2(x+1)-1, 简算得 2x+1
        if y < 0:
            result = temp - abs(y) + x
        if y > 0 and x < 0:
            result = temp - 5*abs(y) + abs(x)
        if y > 0 and x > 0:
            result = temp - 5*abs(y) - abs(x)
        return result


    elif abs(x) > abs(y):
        temp = math.pow((2*abs(x)+1), 2)  # 本质是 2(x+1)-1, 简算得 2x+1
        if x < 0 and y > 0:
            result = temp - 3*abs(x) + y
        if x < 0 and y < 0:
            result = temp - 3*abs(x) - y
        if x > 0 and y > 0:
            result = temp - 7*abs(x) + y
        if x > 0 and y < 0:
            result = temp - 7*abs(x) - y
        return result


    elif abs(x) == abs(y):
        temp = math.pow((2*abs(x)+1), 2)  # 本质是 2(x+1)-1, 简算得 2x+1
        if y < 0 and x > 0:
            result = temp
        if y < 0 and x < 0:
            result = temp - 2*abs(x)
        if y > 0 and x < 0:
            result = temp - 4*abs(x)
        if y > 0 and x > 0:
            result = temp - 6*abs(x)
        return result


    else:
        result = 不可知错误,请检查!!
        return result

if __name__ == "__main__":
    print(int(get_num(-3, -2)))
    print(int(get_num(-2, 3)))
    print(int(get_num(-1, -1)))  # 7
    print(int(get_num(1, 0)))  # 2
    print(int(get_num(1, 1)))  # 3

螺旋队列题解

原文:https://www.cnblogs.com/SBJBA/p/12027630.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!