Search code examples
calgorithmtraversalspiral

C - spiral traversal of 2D array outwards (starting from center) and clockwise


I'm struggling with my assignment and need some help.

The program I have to code must traverse (more exactly - fill with natural numbers from 1 to N^2, but the traversal algorithm is what I struggle with) a 2D array A[N][N], where N is odd (1,3,5,7...), starting from center ( A[N/2][N/2] ) and moving spirally and clockwise.

Example (N=5):

25  10  11  12  13
24  9   2   3   14
23  8   1   4   15
22  7   6   5   16
21  20  19  18  17

I see the pattern : center=1 ; 1xUP, 1xRIGHT, 2xDOWN, 2xLEFT, 3xUP, 3xRIGHT, and so on ...

How can I implement this algorithm with loops? Time is ticking away and I'm stuck here ...

Will be happy to read some suggestions and receive help.

Thank you!


Solution

  • You can use same implementation and change direction of first step here: Print 2-D Array in clockwise expanding spiral from center

    int x = 0; // current position; x
    int y = 0; // current position; y
    int d = 0; // current direction; 0=RIGHT, 1=DOWN, 2=LEFT, 3=UP
    int c = 0; // counter
    int s = 1; // chain size
    

    int d - is current direction; change it to 3.