Rotate the Matrix:
You are given a NxN matrix.You have to rotate same coloured rectangle clockwise or anticlockwise alternatively by a ‘k’ value. K value keeps on increasing by one as we move from outer to inner loop.Suppose in the given figure outermost loop is rotated by 1 place clockwise followed by next loop rotated by 2 places anticlockwise and so on. [Give only Inplace solution].
You are given a NxN matrix.You have to rotate same coloured rectangle clockwise or anticlockwise alternatively by a ‘k’ value. K value keeps on increasing by one as we move from outer to inner loop.Suppose in the given figure outermost loop is rotated by 1 place clockwise followed by next loop rotated by 2 places anticlockwise and so on. [Give only Inplace solution].

// Picture taken from : https://www.geeksforgeeks.org/factset-interview-experience-set-12-campus/
Solution:
#include <iostream>
using namespace std;
#define N 5
void printMatrix(int A[][N]){
for(int i=0; i<N; i++){
for(int j=0; j<N; j++)
cout<<A[i][j]<<' ';
cout<<endl;
}
}
void rotateMatrix(int A[][N]){
int l = 0, r = N-1, t = 0, b = N-1;
int k = 1;
bool isClockwise = true;
//iterating each ring (rectangle)
while(l<r){
// rotating the respective rectangle k times
for(int c=1; c<=k; c++){
//storing corner values of respective rectangle
int tl = A[t][l], tr = A[t][r], bl = A[b][l], br = A[b][r];
// if clockwise rotation is needed
if(isClockwise){
for(int i=r-1; i>l; i--) A[t][i+1] = A[t][i];
for(int i=b-1; i>t; i--) A[i+1][r] = A[i][r];
for(int i=l+1; i<r; i++) A[b][i-1] = A[b][i];
for(int i=t+1; i<b; i++) A[i-1][l] = A[i][l];
// now placing the stored temporary variables at correct place
A[t][l+1] = tl; A[t+1][r] = tr; A[b][r-1] = br; A[b-1][l] = bl;
}
// if antiClockwise rotation is needed
else{
for(int i=l+1; i<r; i++) A[t][i-1] = A[t][i];
for(int i=b-1; i>t; i--) A[i+1][l] = A[i][l];
for(int i=r-1; i>l; i--) A[b][i+1] = A[b][i];
for(int i=t+1; i<b; i++) A[i-1][r] = A[i][r];
// now placing the stored temporary variables at correct place
A[t][r-1] = tr; A[t+1][l] = tl; A[b][l+1] = bl; A[b-1][r] = br;
}
}
// moving to inner rectangle and changing the rotation direction and
// increasing value of k by 1
// increasing value of k by 1
l++; r--; t++; b--; isClockwise = !isClockwise; k++;
}
}
int main()
{
int A[][N] = {
{ 1, 2, 3, 4, 5},
{16, 17,18, 19, 6},
{15, 24, 25, 20, 7},
{14, 23, 22, 21, 8},
{13, 12, 11, 10, 9}
};
cout<<"Printing before rotation:"<<endl;
printMatrix(A);
rotateMatrix(A);
cout<<"Printing after rotation:"<<endl;
printMatrix(A);
return 0;
}
Enjoy learning.
Comments
Post a Comment