循环以螺旋 [英] Looping in a spiral
问题描述
有一个朋友是需要一个算法,将让他遍历一个N×M的矩阵元素(N和M都是奇数)。我想出了一个解决方案,但我想看看我的同胞SO'ers可以用一个更好的解决方案上来。
A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fellow SO'ers could come up with a better solution.
我张贴我的解决方案为这个问题的答案。
I'm posting my solution as an answer to this question.
示例输出:
对于一个3x3矩阵,输出应该是:
For a 3x3 matrix, the output should be:
(0,0) (1,0) (1,1) (0,1) (-1,1) (-1,0) (-1,-1) (0,-1) (1,-1)
(0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1)
此外,该算法应支持非方阵,所以例如用于5×3矩阵,输出应该是:
Furthermore, the algorithm should support non-square matrices, so for example for a 5x3 matrix, the output should be:
(0,0) (1,0) (1,1) (0,1) (-1,1) (-1,0) (-1,-1) (0,-1) (1,-1) (2,-1) (2,0) (2,1) (-2,1) (-2,0) (-2,-1)
(0, 0) (1, 0) (1, 1) (0, 1) (-1, 1) (-1, 0) (-1, -1) (0, -1) (1, -1) (2, -1) (2, 0) (2, 1) (-2, 1) (-2, 0) (-2, -1)
推荐答案
下面是我的解决方案(在Python):
Here's my solution (in Python):
def spiral(X, Y):
x = y = 0
dx = 0
dy = -1
for i in range(max(X, Y)**2):
if (-X/2 < x <= X/2) and (-Y/2 < y <= Y/2):
print (x, y)
# DO STUFF...
if x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y):
dx, dy = -dy, dx
x, y = x+dx, y+dy
这篇关于循环以螺旋的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!