问题描述
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Example 2:
问题分析
该问题给出了一个n*n的二维矩阵来表示一幅图形,然后要求在原矩阵上将图片旋转90度,并且题目规定了不能申请另外的矩阵来进行旋转,要在原矩阵上进行旋转,所以我们首先要找到旋转后的矩阵数值与与原矩阵数值最表对应的关系,由上图我们可以看到
A[0][0] -> A[0][3]
A[1][0] -> A[0][2]
A[0][1] -> A[1][3]
A[2][0] -> A[0][1]
A[0][2] -> A[2][3]
A[3][0] -> A[0][0]
A[0][3] -> A[3][3]
由此可得:对于n * n 的2维矩阵,旋转变换关系为:
A[i][j] -> A[j][n-1-i]
代码展示
int i,j,temp;
int n=matrix.size();
for(i = 0;i < n/2;++i) {
for (j = i;j < n-1-i;++j) {
temp = matrix[j][n-i-1];
matrix[j][n-i-1] = matrix[i][j];
matrix[i][j] = matrix[n-j-1][i];
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1] = temp;
}//for
}//for
运行结果展示