Rotate Image
Q:You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
顺时针90度旋转矩阵。in place
A:分两步走:1.沿着主对角线交换两侧的对称元素,2.交换第j列和第n-1-j列。
PS:如果是逆时针旋转,则1.沿着主对角线交换两侧的对称元素,2.交换第i行和第n-1-i行
void rotate(vector<vector<int> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = matrix.size();
int i,j;
int tmp;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for(int j=0;j<n/2;j++)
{
for(int i=0;i<n;i++)
{
tmp = matrix[i][j];
matrix[i][j] = matrix[i][n-1-j];
matrix[i][n-1-j] = tmp;
}
}
}
浙公网安备 33010602011771号