首页 » 编程之美 » 正文

[leetcode_48]Rotate Image

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

class Solution {
public:
    void MoveStep(vector<vector<int>> &matrix,int i,int j,int n)
    {
        int x1 = i;
        int y1 = j;</p>

<pre><code>    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&amp;lt;vector&amp;lt;int&amp;gt; &amp;gt; &amp;amp;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 &amp;lt; n;i++)
        {
            for(int j = 0;j &amp;lt; n;j++)
            {
                MoveStep(matrix,i,j,length-1);
            }
        }
    }
    else
    {
        for(int i = 0;i &amp;lt; n;i++)
        {
            for(int j = 0;j &amp;lt;= n;j++)
            {
                MoveStep(matrix,i,j,length-1);
            }
        }
    }
}
</code></pre>

<p>};

发表评论