在某人工智能培训班看到这个预热练习,继续玩一下~
题目意思是有一个螺旋存储的正整数矩阵,求矩阵中任意数到数字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 24 25—> …
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转1圈为一个矩阵,搭建坐标系如下图:
围绕中心1转n圈,最后一个数字是(2n-1)的平方,矩阵的每边长度是2*(n-1),而此时中心1的坐标是(n,n)
输入数字后,先找出大于它的下一个平方数,然后按矩阵变长的规律找出这个数字在那一条边,进而推出其坐标,再求到(n,n)的距离
下面是完整代码:
ip = eval(input())
#找出大于input的下一个平方数
n = 0
nsq = (2*n-1)**2
x,y = 0,0
while ip>nsq:
n+=1
nsq=pow(2*n-1,2)
#找出矩阵四个顶点的数字
dimon1 = nsq-(2*(n-1))
dimon2 = nsq-2*(2*(n-1))
dimon3 = nsq-3*(2*(n-1))
dimon4 = nsq-4*(2*(n-1))
#找出input在矩阵哪条边上,进而得到坐标
if dimon1 < ip <= nsq:
x = ip - dimon1
y = 0
elif dimon2 < ip <= dimon1:
x = 0
y = dimon1-ip
elif dimon3 < ip <= dimon2:
x = dimon2-ip
y = 2*(n-1)
elif dimon4< ip <= dimon3:
x = 2*(n-1)
y = ip-dimon4
#求曼哈顿距离
dist=abs(x-n+1)+abs(y-n+1)
print('The Manhattan Distance is {}'.format(dist))
最后,看到一位大佬的版本,非常不同:
https://www.cnblogs.com/jason-Gan/p/11011892.html
大半夜的搞出来很开心,可以去睡觉了,困爆了。。。
继续求大佬指教嘤~
Have fun~