Tuesday, 19 July 2016

Inplace rotate square matrix by 90 degrees(Anti-Clockwise)

/*  Inplace rotate square matrix by 90 degrees */
/*
Given an square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.

Example:
Input:
 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15 16
Output:
 4  8 12 16
 3  7 11 15
 2  6 10 14
 1  5  9 13
 */


 #include<iostream>  
 using namespace std;  
 int N = 4;  
 void printMatrix(int mat[4][4]){  
  for (int i = 0; i < N; i++) {  
  for (int j = 0; j < N; j++)  
   cout << mat[i][j] << " ";  
  cout << endl;  
  }  
  cout << endl;  
 }  
 void rotateMatrix(int mat[4][4], int N){  
   for(int i = 0; i < N / 2; i++){  
     for(int j = i; j < N - 1 - i; j++){  
       //store the top in temp  
       int temp = mat[i][j];  
       //move the right to the top  
       mat[i][j] = mat[j][N - 1 - i];  
       //move bottom to right  
       mat[j][N - 1 - i] = mat[N - 1 - i][N - 1 - j];  
       //move left to bottom  
       mat[N - 1 - i][N - 1 - j] = mat[N - 1 - j][i];  
       //move top stored in temp to left  
       mat[N - 1 - j][i] = temp;  
     }  
   }  
 }  
 int main(){  
   int mat[4][4] =  
  {  
  {1, 2, 3, 4},  
  {5, 6, 7, 8},  
  {9, 10, 11, 12},  
  {13, 14, 15, 16}  
  };  
  printMatrix(mat);  
  rotateMatrix(mat, 4);  
  printMatrix(mat);  
  return 0;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive