tags:

views:

330

answers:

2

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

A: 

You could create a second array and then copy the first one into the second one by reading row-major in the first one and writing column-major to the second one.

So you would copy:

1  2  3
4  5  6
7  8  9

and you would read the first row then write it back up starting like:

3
2
1
samoz
+8  A: 
for(int i=0; i<n/2; i++)
   for(int j=0; j<(n+1)/2; j++)
       cyclic_roll(a[i][j], a[n-1-j][i], a[n-1-i][n-1-j], a[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.

Pavel Radzivilovsky
could you explain on how did you come up with the indexes ?
Passionate programmer
Explaining the indexes.. well, think where the location at (i,j) goes when rotating 90 degrees. Just imagine the picutre. (i,j)->(end-j, i). As high as the original was far from the left, and as far from the left as it was from the bottom of the matrix.
Pavel Radzivilovsky
If one rotates counter-clockwise, the mapping is a[p][k] --> a[N-1-k][p] --> a[N-1-p][N-1-k] --> a[k][N-1-p]. I think there is also an error in the constrain for i. It should be i < n/2 in the for loop (for j it's ok). Look at the 3x3 example below. Number 4 gets taken care of, when rotating 2. You don't want to rotate for i = 1 and j = 0 again.
Maciej Hehl
I can't edit. The code should befor(int i=0; i < N/2; i++) for(int j=0; j < (N+1)/2; j++) cyclic_roll(a[i][j], a[N-1-j][i], a[N-1-i][N-1-j], a[j][N-1-i]);
Maciej Hehl
The third parameter to the cyclic_roll function still needs a correction. It Should be a[n-1-i][n-1-j] :)
Maciej Hehl
thanks again, fixed
Pavel Radzivilovsky