Advertisement
audreych

12928 - Matrix Rotation

Jan 24th, 2021
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int initial[105][105];
  4. int arr[105][105];
  5.  
  6. int main(){
  7.     int row, col;
  8.     int flag = 1;
  9.     scanf("%d %d", &row, &col);
  10.     for(int i = 0; i < row; i++){
  11.         for(int j = 0; j < col; j++){
  12.             scanf("%d", &initial[i][j]);
  13.         }
  14.     }
  15.     int rotate;
  16.     scanf("%d", &rotate);
  17.     rotate = rotate % 4; //because the 4th rotate will always be back to the original array
  18.     if( rotate == 0) {
  19.         for(int i = 0; i < row; i++){
  20.             for(int j = 0; j < col; j++){
  21.                 arr[i][j] = initial[i][j];
  22.             }
  23.         }
  24.         flag = 0;
  25.     } else if(rotate == 1){
  26.         for(int i = 0; i < col; i++){
  27.             for(int j = 0; j < row; j++){
  28.                 arr[i][j] = initial[row - 1 - j][i];   
  29.             }
  30.         }
  31.         flag = 1;
  32.     } else if(rotate == 2){
  33.         for(int i = 0 ;  i < row; i++){
  34.             for(int j = 0; j < col; j++){
  35.                 arr[i][j] = initial[row - 1 - i][col -1 - j];
  36.             }
  37.         }
  38.         flag = 0;
  39.     } else if(rotate == 3){
  40.         for(int i = 0; i < col; i++){
  41.             for(int j = 0; j < row; j++){
  42.                 arr[i][j] = initial[j][col - 1 - i];
  43.             }
  44.         }
  45.         flag = 1;
  46.     }
  47.     // swap row and col when flag is 1
  48.     // because I switched the row and col during the initialization process when flag is 1
  49.     // will overprint if I don't
  50.     if(flag == 1){
  51.         int temp = row;
  52.         row = col;
  53.         col = temp;
  54.     }
  55.     // printing
  56.     for(int i = 0; i < row; i++){
  57.         for(int j = 0 ; j < col; j++){
  58.             if(j != col - 1){
  59.                 printf("%d ", arr[i][j]);
  60.             } else {
  61.                 printf("%d\n", arr[i][j]);
  62.             }
  63.         }
  64.     }
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement