地址:http://oj.leetcode.com/problems/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?
注意题目要求用O(1)的外部空间
顺时间转90°其实就是ai,j 转到 aj, n-1-i, 后者转到 an-1-i, n-1-j, 后者在转到an-1-j, i 后者再转到ai, j
画了一幅图,只要从这四分之一的扇形开始处理即可。扇形上实下虚。
参考代码:
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
if(matrix.empty())
return;
int n = matrix.size();
for(int i = 0; i<n; ++i)
{
for(int j = 0; j<=i&&j<n-i-1; ++j)
{
int tmp = matrix[i][j];
matrix[i][j] = matrix[n-1-j][i];
matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
matrix[j][n-1-i] = tmp;
}
}
}
};