首页 > 代码库 > LeetCode[Array]: Rotate Image

LeetCode[Array]: Rotate Image

You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?

参考LeetCode[Array]: Spiral Matrix II的迭代思路,先完成最外环的旋转,然后依次旋转内环。我的C++代码如下:

void rotate(vector<vector<int> > &matrix) {
    int beginRow = 0, endRow = matrix.size() - 1, beginCol = 0, endCol = matrix[0].size() - 1;
    while (beginRow <= endRow && beginCol <= endCol) {
        for (int i = 0; i < endCol - beginCol; ++i) {
            int tmp                               = matrix[beginRow    ][beginCol + i];
            matrix[beginRow    ][beginCol + i] = matrix[  endRow - i][beginCol      ];
            matrix[  endRow - i][beginCol    ] = matrix[  endRow    ][  endCol - i];
            matrix[  endRow    ][  endCol - i] = matrix[beginRow + i][  endCol    ];
            matrix[beginRow + i][  endCol    ] = tmp;
        }

        ++beginRow; --endRow;
        ++beginCol; --endCol;
    }
}


在Discuss上看到一个比较奇特的解法,其思路是:首先将矩阵上下倒置,然后沿左上到右下的对角线对折即可完成旋转,其C++代码实现非常简洁:

void rotate(vector<vector<int> > &matrix) 
{
    reverse(matrix.begin(), matrix.end());
    for (unsigned i = 0; i < matrix.size(); ++i)
        for (unsigned j = i+1; j < matrix[i].size(); ++j)
            swap (matrix[i][j], matrix[j][i]);
}


LeetCode[Array]: Rotate Image