How to rotate a N x N matrix by 90 degrees. I want it to be inplace?
Rotate Matrix 90 Degree Clockwise or Right Rotation The rotation of a matrix involves two steps: First, find the transpose of the given matrix. Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.
Approach to solve this problem Take Input of a square matrix. Find the transpose of the matrix. Swap the element at index 0 with index n-1. Return the output.
for(int i=0; i<n/2; i++) for(int j=0; j<(n+1)/2; j++) cyclic_roll(m[i][j], m[n-1-j][i], m[n-1-i][n-1-j], m[j][n-1-i]); void cyclic_roll(int &a, int &b, int &c, int &d) { int temp = a; a = b; b = c; c = d; d = temp; }
Note I haven't tested this, just compoosed now on the spot. Please test before doing anything with it.
here is my solution: (rotate pi/2 clockwise)
do the transpose of the array, (like matrix transpose)
reverse the elements for each row
cons int row = 10; cons int col = 10; //transpose for(int r = 0; r < row; r++) { for(int c = r; c < col; c++) { swap(Array[r][c], Array[c][r]); } } //reverse elements on row order for(int r = 0; r < row; r++) { for(int c =0; c < col/2; c++) { swap(Array[r][c], Array[r][col-c-1]) } }
if rotate pi/2 in counter-clockwise
transpose the array
reverse the elements on column order
never test the code! any suggestion would be appreciated!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With