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] ]题目要求不能额外开辟另一个2D矩阵,不然直接把第n列放到第n行就行了。
解题思路:
- 先求原矩阵的转置矩阵(以对角线进行对称)
[ [
[1,2,3], [1,4,7],
[4,5,6], —> [2,5,8],
[7,8,9] [3,6,9]
] ]
2.将每一行逆序就是要求的结果
C++版本
void rotate(vector<vector<int>>& matrix) {
int temp;
for(int i = 0;i < matrix.size();i++){
for(int j = 0;j < matrix.size();j++){
if(i < j){ //转置