Algorithm for iterating over an outward spiral on a discrete 2D grid from the origin

前端 未结 12 1705
独厮守ぢ
独厮守ぢ 2020-12-05 06:54

For example, here is the shape of intended spiral (and each step of the iteration)

          y
          |
          |
   16 15 14 13 12
   17  4  3  2 11
--         


        
12条回答
  •  情书的邮戳
    2020-12-05 07:26

    This problem is best understood by analyzing how changes coordinates of spiral corners. Consider this table of first 8 spiral corners (excluding origin):

     x,y   |  dx,dy  | k-th corner | N | Sign |
    ___________________________________________
    1,0    |  1,0    | 1           | 1 |  +
    1,1    |  0,1    | 2           | 1 |  +
    -1,1   |  -2,0   | 3           | 2 |  -
    -1,-1  |  0,-2   | 4           | 2 |  -
    2,-1   |  3,0    | 5           | 3 |  +
    2,2    |  0,3    | 6           | 3 |  +
    -2,2   |  -4,0   | 7           | 4 |  -
    -2,-2  |  0,-4   | 8           | 4 |  -
    

    By looking at this table we can calculate X,Y of k-th corner given X,Y of (k-1) corner:

    N = INT((1+k)/2)
    Sign = | +1 when N is Odd
           | -1 when N is Even
    [dx,dy] = | [N*Sign,0]  when k is Odd
              | [0,N*Sign]  when k is Even
    [X(k),Y(k)] = [X(k-1)+dx,Y(k-1)+dy]
    

    Now when you know coordinates of k and k+1 spiral corner you can get all data points in between k and k+1 by simply adding 1 or -1 to x or y of last point. Thats it.

    good luck.

提交回复
热议问题