How do you rotate a two dimensional array?

后端 未结 30 3093
耶瑟儿~
耶瑟儿~ 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:39

    Here is my attempt for matrix 90 deg rotation which is a 2 step solution in C. First transpose the matrix in place and then swap the cols.

    #define ROWS        5
    #define COLS        5
    
    void print_matrix_b(int B[][COLS], int rows, int cols) 
    {
        for (int i = 0; i <= rows; i++) {
            for (int j = 0; j <=cols; j++) {
                printf("%d ", B[i][j]);
            }
            printf("\n");
        }
    }
    
    void swap_columns(int B[][COLS], int l, int r, int rows)
    {
        int tmp;
        for (int i = 0; i <= rows; i++) {
            tmp = B[i][l];
            B[i][l] = B[i][r];
            B[i][r] = tmp;
        }
    }
    
    
    void matrix_2d_rotation(int B[][COLS], int rows, int cols)
    {
        int tmp;
        // Transpose the matrix first
        for (int i = 0; i <= rows; i++) {
            for (int j = i; j <=cols; j++) {
                tmp = B[i][j];
                B[i][j] = B[j][i];
                B[j][i] = tmp;
            }
        }
        // Swap the first and last col and continue until
        // the middle.
        for (int i = 0; i < (cols / 2); i++)
            swap_columns(B, i, cols - i, rows);
    }
    
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        int B[ROWS][COLS] = { 
                      {1, 2, 3, 4, 5}, 
                          {6, 7, 8, 9, 10},
                              {11, 12, 13, 14, 15},
                              {16, 17, 18, 19, 20},
                              {21, 22, 23, 24, 25}
                            };
    
        matrix_2d_rotation(B, ROWS - 1, COLS - 1);
    
        print_matrix_b(B, ROWS - 1, COLS -1);
        return 0;
    }
    

提交回复
热议问题