求整数数列螺旋存储中任意数到数据1的曼哈顿距离 spiral_memory

1. Spiral Memory
You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then
counting up while spiraling outward. For example, the first few squares are allocated like this:
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23---> …
While this is very space-efficient (no squares are skipped), requested data must be carried back to
square 1 (the location of the only access port for this memory system) by programs that can only
move up, down, left, or right. They always take the shortest path: the Manhattan Distance between
the location of the data and square 1.
For example:
Data from square 1 is carried 0 steps, since it's at the access port.
Data from square 12 is carried 3 steps, such as: down, left, left.
Data from square 23 is carried only 2 steps: up twice.
Data from square 1024 must be carried 31 steps.
How many steps are required to carry the data from the square identified in your puzzle input all
the way to the access port?
How to test your answer:
If you input: 100000 Your Answer should be: 173
If you input: 2345678 Your Answer should be: 1347

"""
题目: 螺旋存储,求任意数到数字1的曼哈顿距离
17  16  15  14  13
18  5   4   3   12
19  6   1   2   11
20  7   8   9   10
21  22  23  --> ...

先解释下螺旋存储,其实就是数据按正方形边逆时针排列
比如1维:
1

比如2维:
4   3
1   2

比如3维:
5   4   3
6   1   2
7   8   9

曼哈顿距离就是 该数字和1 的水平距离加垂直距离.

这里大概讲下下述代码的解题思路:
首先求 任意数据和1的曼哈顿距离,那么首先我们要知道该数字和1在上述螺旋存储的相对位置, 这里我把数字根据它处的正方形的边长成为维度((数在n-1_平方到n平方之间的维度为n), 然后就可以先总结出各个维度下 1 的行列,
比如
1维时 1的行列是(1,1)
2维时 1的行列是(2,1)
3维时 1的行列是(2,2)
4维时 1的行列是(3,2)
5维时 1的行列是(3,3)
6维时 1的行列是(4,3)
行是维度整除2 再加1, 列是维度除以2向上取整.
再就是处理 任意数字本身的行列坐标, 大概思路就是以所在维度的最大数即n平方为参考, 奇数维度的n平方值的行列坐标(n,n), 偶数维度的n平方值的行列坐标(1,1),然后根据该值维度的最大值和值的差值安装大到小
或小到大的规律,确定该值本身的行列坐标
""" from math import sqrt, ceil def distance(x): # x的维度 dim = ceil(sqrt(x)) # print(dim) # 1 所在的行列 row_1 = dim//2+1 col_1 = ceil(dim/2) # print(row_1,col_1) # x所在的行列 if dim%2 == 0: # 如果是偶数维度 if dim**2-x <= (dim-1): row_x = 1 col_x = 1+dim**2-x else: row_x = dim**2-dim-x+2 col_x = dim # print(row_x,col_x) else: # 如果是奇数维度 if dim**2-x <= (dim-1): row_x = dim col_x = x+dim-dim**2 else: row_x = x-(dim-1)**2 col_x = 1 # print(row_x,col_x) # x和1的曼哈度距离 distance = abs(row_x-row_1)+abs(col_x-col_1) print('The Manhattan Distance between the data {} and square 1 is: {}'.format(x, distance)) if __name__ == '__main__': while True: x = int(input('Please enter an integer greater than zero : ')) distance(x) # 输入输出结果如下: # Please enter an integer greater than zero : 100000 # The Manhattan Distance between the data 100000 and square 1 is: 173 # Please enter an integer greater than zero : 2345678 # The Manhattan Distance between the data 2345678 and square 1 is: 1347
<人追求理想之时,便是坠入孤独之际.> By 史泰龙
原文地址:https://www.cnblogs.com/jason-Gan/p/11011892.html