简体   繁体   中英

rotate a 2d array right

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?

Well, the snippet shown actually turns it clock-wise (ie, 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. )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM