Reputation: 577
I have the following code that seems to rotate a matrix left 90 degrees... But what I'm after is rotating it right not left :D tried modding it but keep messing things up...
public static int[,] RotateMatrix(int[,] matrix, int n)
{
int[,] ret = new int[n, n];
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
ret[i, j] = matrix[n - j - 1, i];
}
}
return ret;
}
How do I rotate it right?
Upvotes: 2
Views: 1461
Reputation: 106375
Well, the snippet shown actually turns it clock-wise (i.e., to the right)... But if you want to go in another direction, just swap the coordinates:
ret[i, j] = matrix[j, n - i - 1];
It's actually quite easy, if you think about it for a moment. Let's imagine you have this 4x4 matrix:
===========================>
| 0,0 | 0,1 | 0,2 | 0,3 | J
| 1,0 | 1,1 | 1,2 | 1,3 |
| 2,0 | 2,1 | 2,2 | 2,3 |
| 3,0 | 3,1 | 3,2 | 3,3 |
=========================
| I
V
And now, instead of rotating the matrix, rotate the axis around it:
<===========================
I | 0,0 | 0,1 | 0,2 | 0,3 |
| 1,0 | 1,1 | 1,2 | 1,3 |
| 2,0 | 2,1 | 2,2 | 2,3 |
| 3,0 | 3,1 | 3,2 | 3,3 |
=========================
J |
V
See what happens? The vertical one remains the same, it just changed its name (from I to J). And the horizontal one not only changed its name, but also went to the other side: and that's exactly what's expressed by n - j - 1
formula. )
And exactly the same mind trick will help you grok the formula for rotating the matrix counter clockwise. )
Upvotes: 4