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?
solution: 实地画一个矩阵,顺时针翻转90度,结果可以以这样两步得到,1,以(0,0)(1,1)...(n,n)为轴旋转180度,即x,y坐标互换;2,180度翻转该矩阵,即y保持不变,x变为n-x。
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(matrix[0].size() <= 1)
return;
int len = matrix[0].size();
for (int i = 0; i < len - 1; i++)
{
for (int j = i + 1; j < len; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len / 2; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[i][len - 1 - j];
matrix[i][len - 1 - j] = temp;
}
}
}
};