Print 2-D Array in clockwise expanding spiral from center

前端 未结 4 1883
离开以前
离开以前 2020-12-02 00:18

I have an guaranteed to be a perfect square matrix. I want to start at the center of the matrix in this case it would be matrix[2][2], I know h

4条回答
  •  旧时难觅i
    2020-12-02 01:16

    Let's identify the patterns first ..

    Even-Size Square Matrix, Example: 4x4

      07 > 08 > 09 > 10
      ^               v
      06  (01)> 02   11
      ^          v    v
      05 < 04 < 03   12
                      v
     [16]< 15 < 14 < 13
    
    Starting Point: [2, 2] ~ [SIZE/2, SIZE/2]
    
    Ending Point: [4, 1] ~ [SIZE, 1]
    
    Chains: Count(K-chain)=2 for K = 1..(SIZE-2)
            + 3 for Count = SIZE-1
    

    Odd-Size Square Matrix, Example: 5x5

      21 > 22 > 23 > 24 >[25]
      ^
      20   07 > 08 > 09 > 10
      ^    ^               v
      19   06  (01)> 02   11
      ^    ^          v    v
      18   05 < 04 < 03   12 
      ^                    v
      17 < 16 < 15 < 14 < 13
    
    Starting Point: [2, 2] ~ [⌊SIZE/2⌋, ⌊SIZE/2⌋]
    
    Ending Point: [1, 5] ~ [1, SIZE]
    
    Chains: Count(K-chain)=2 for K = 1..(SIZE-2)
            + 3 for Count = SIZE-1
    

    Live Code

    void print_spiral (int ** matrix, int size)
    {
        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
    
        // starting point
        x = ((int)floor(size/2.0))-1;
        y = ((int)floor(size/2.0))-1;
    
        for (int k=1; k<=(size-1); k++)
        {
            for (int j=0; j<(k<(size-1)?2:3); j++)
            {
                for (int i=0; i

提交回复
热议问题