问题描述:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
要求不能另开空间,一开始理解错了,后来画图明白了
解题思路:
首先以对角线为轴对称交换,再以中间列(如果有的话)为轴对称交换
a b c d
e f g h
i j k l
m n o p
a e i m
b f j n
c g k o
d h l p
m i e a
n j f b
o k g c
p l h d
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
if (matrix.empty())
return;
int n = matrix.size(), tmp;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for (int i = 0; i < n/2; ++i) {
for (int j = 0; j < n; ++j) {
tmp = matrix[i][j];
matrix[i][j] = matrix[n-1-i][j];
matrix[n-1-i][j] = tmp;
}
}
return;
}
};