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
ide
""" 題目: 螺旋存儲,求任意數到數字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