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> &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> &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]); }