Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate a N x N matrix by 90 degrees? [closed]

Tags:

c++

algorithm

How to rotate a N x N matrix by 90 degrees. I want it to be inplace?

like image 910
Passionate programmer Avatar asked May 23 '10 19:05

Passionate programmer


People also ask

How do you rotate a matrix by 90?

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.

How do you rotate a matrix 90 degrees anticlockwise in Java?

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.


2 Answers

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.

like image 57
Pavel Radzivilovsky Avatar answered Oct 14 '22 10:10

Pavel Radzivilovsky


here is my solution: (rotate pi/2 clockwise)

  1. do the transpose of the array, (like matrix transpose)

  2. 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

  1. transpose the array

  2. reverse the elements on column order

never test the code! any suggestion would be appreciated!

like image 22
elliptic00 Avatar answered Oct 14 '22 12:10

elliptic00