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]
]
矩阵旋转问题,再浏览题目时发现了这个题,觉得一直很困扰我,因为没有解决这种问题的思路,再思考了一会后,还是按照原来的硬解思路来,就是没有一个算法思路,这样是不行的,所以就干脆直接再discuss里面进行学习。
思路是先将矩阵的行逆转,然后以左上角为中心点,不断交换中心点所在行列的坐标。
比如,流程如下:
[ [ [ [ [
[1,2,3], [7,8,9], [7,4,1], [7,4,1], [7,4,1],
[4,5,6], [4,5,6], [8, [8,5,2], [8,5,2],
[7,8,9] [1,2,3] [9, [9,6, [9,6,3],
] ] ] ] ]
代码:
void rotate(vector<vector<int>>& matrix) {
reverse(matrix.begin(),matrix.end());
for(int i=0;ifor(int j=i+1;j0].size();j++){
swap(matrix[i][j],matrix[j][i]);
}
}
}
这次行逆转变成了列逆转,在将矩阵的列逆转了以后,继续以左上角为中心进行调换。
[ [ [ [ [
[1,2,3], [3,2,1], [3,6,9], [3,6,9], [3,6,9],
[4,5,6], [6,5,4], [2, [2,5,8], [2,5,8],
[7,8,9] [9,8,7] [1, [1,4, [1,4,7],
] ] ] ] ]
代码:
void rotate(vector<vector<int>>& matrix) {
for(int i=0;ifor(int j=0;j<(int)matrix.size()/2;j++){
swap(matrix[i][j],matrix[i][matrix.size()-j-1]);
}
}
for(int i=0;ifor(int j=i+1;j0].size();j++){
swap(matrix[i][j],matrix[j][i]);
}
}
}
上下逆转,左右逆转,顺序无所谓,比如下面就是先列后行。
[ [ [
[1,2,3], [3,2,1], [9,8,7],
[4,5,6], [6,5,4], [6,5,4],
[7,8,9] [9,8,7] [3,2,1]
] ] ]
代码:
void rotate(vector<vector<int>>& matrix) {
for(int i=0;ifor(int j=0;j<(int)matrix.size()/2;j++){
swap(matrix[i][j],matrix[i][matrix.size()-j-1]);
}
}
reverse(matrix.begin(),matrix.end());
}