How do you rotate a two dimensional array?

后端 未结 30 3585
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

Inspired by Raymond Chen\'s post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I\'d

30条回答
  •  不要未来只要你来
    2020-11-22 03:33

    From a linear point of view, consider the matrices:

        1 2 3        0 0 1
    A = 4 5 6    B = 0 1 0
        7 8 9        1 0 0
    

    Now take A transpose

         1 4 7
    A' = 2 5 8
         3 6 9
    

    And consider the action of A' on B, or B on A'.
    Respectively:

          7 4 1          3 6 9
    A'B = 8 5 2    BA' = 2 5 8
          9 6 3          1 4 7
    

    This is expandable for any n x n matrix. And applying this concept quickly in code:

    void swapInSpace(int** mat, int r1, int c1, int r2, int c2)
    {
        mat[r1][c1] ^= mat[r2][c2];
        mat[r2][c2] ^= mat[r1][c1];
        mat[r1][c1] ^= mat[r2][c2];
    }
    
    void transpose(int** mat, int size)
    {
        for (int i = 0; i < size; i++)
        {
            for (int j = (i + 1); j < size; j++)
            {
                swapInSpace(mat, i, j, j, i);
            }
        }
    }
    
    void rotate(int** mat, int size)
    {
        //Get transpose
        transpose(mat, size);
    
        //Swap columns
        for (int i = 0; i < size / 2; i++)
        {
            for (int j = 0; j < size; j++)
            {
                swapInSpace(mat, i, j, size - (i + 1), j);
            }
        }
    }
    

提交回复
热议问题