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.
题意:
给一个 n x n的矩阵,要求我们就在此矩阵空间上将这个矩阵顺时针旋转90度。
比如给的例子
[
[1,2,3],
[4,5,6],
[7,8,9]
],
我们最终要把它变成
[
[7,4,1],
[8,5,2],
[9,6,3]
]
解法步骤:
方法有很多,这里只给出一种解法。
- 先求原矩阵的转置矩阵,比如例子给出的矩阵的转置矩阵为
[
[1,4,7],
[2,5,8],
[3,6,9]
] - 将转置矩阵的每一行的数字翻转,得到最终结果。
[
[7,4,1],
[8,5,2],
[9,6,3]
]
C++实现
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
if(matrix.size()==0||matrix.size()==1)
return;
for(int i=0;i<matrix.size();++i)
{
for(int j=i+1;j<matrix[i].size();++j)
{
swap(matrix[i][j],matrix[j][i]);
}
}
for(int i=0;i<matrix.size();++i)
{
reverse(matrix[i].begin(),matrix[i].end());
}
}
};
Java实现
class Solution {
public void rotate(int[][] matrix) {
for(int i=0;i<matrix.length;++i)
{
for(int j=i+1;j<matrix[0].length;++j)
{
int temp = 0;
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for(int i=0;i<matrix.length;++i)
{
for(int j=0;j<matrix.length/2;++j)
{
int temp = 0;
temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix.length-1-j];
matrix[i][matrix.length-1-j] = temp;
}
}
}
}