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:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
来源:力扣(LeetCode)
解题
给定数组,原地顺时针循转90度;
解法1:先ij=ji,然后每行倒叙即可
ij交换只要做斜着一半即可,不然又会交换回来;
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
//先ij=ji交换,再倒叙每一行即可
int n=matrix.size();
int tmp;
for(int i=0;i<n;i++)
for(int j=i;j<n;j++)
swap(matrix[i][j],matrix[j][i]);
for(int i=0;i<n;i++)
reverse(matrix[i].begin(),matrix[i].end());
}
};
解法2:用大小为4的数组,存放没边一个数字,从外圈到内圈右移一次
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
rot.resize(4);
int n=matrix.size();
for(int j=0;j<(n+1)/2;j++)
for(int i=j;i<n-1-j;i++)//n-1不用换 //从外圈到内圈
{
rot={matrix[j][i],matrix[i][n-1-j],matrix[n-1-j][n-1-i],matrix[n-1-i][j]};
matrix[j][i]=rot[3];
matrix[i][n-1-j]=rot[0];
matrix[n-1-j][n-1-i]=rot[1];
matrix[n-1-i][j]=rot[2];
}
}
private:
vector<int> rot;
};
解法2优化
用tmp将四个角全部交换即可;
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n=matrix.size();
int tmp;
for(int j=0;j<(n+1)/2;j++)
for(int i=j;i<n-1-j;i++)//n-1不用换 //从外圈到内圈
{
tmp=matrix[j][i];
matrix[j][i]=matrix[n-1-i][j];
matrix[n-1-i][j]=matrix[n-1-j][n-1-i];
matrix[n-1-j][n-1-i]=matrix[i][n-1-j];
matrix[i][n-1-j]=tmp;
}
}
};
注意点
转圈时注意用ij表示坐标;