[leetcode_48]Rotate Image

将一个n*n的矩阵顺时针旋转90度,额外地,能不能原地旋转,就是不开辟额外的空间。
一次AC, 每个位置上的旋转只会影响4个位置上的数组,开一个tmp,搞定。
附上代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
    void MoveStep(vector<vector<int>> &matrix,int i,int j,int n)
    {
        int x1 = i;
        int y1 = j;
    
        int x2 = y1;
        int y2 = n - x1;

        int x3 = n - x1;
        int y3 = n - y1;

        int x4 = n - y1;
        int y4 = x1;

        int tmp = matrix[x4][y4];
        matrix[x4][y4] = matrix[x3][y3];
        matrix[x3][y3] = matrix[x2][y2];
        matrix[x2][y2] = matrix[x1][y1];
        matrix[x1][y1] = tmp;
    }
    
    void rotate(vector<vector<int>> &matrix) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int length = matrix.size();
        int n = length / 2;
        if(length % 2 == 0)
        {
            for(int i = 0; i < n; i++)
            {
                for(int j = 0; j < n; j++)
                {
                    MoveStep(matrix, i, j, length-1);
                }
            }
        }
        else
        {
            for(int i = 0; i < n; i++)
            {
                for(int j = 0; j <= n; j++)
                {
                    MoveStep(matrix, i, j, length-1);
                }
            }
        }
    }
};
Licensed under CC BY-NC-SA 4.0