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?
对一个n*n的matrix顺时针旋转90,
step1:switch colums with rows
step2:switch columns
class Solution {
//step1: switch columns to rows
//step2: switch columns
public:
void rotate(vector<vector<int>>& matrix) {
//sanity check
if (matrix.size() <= 1) return;
//step1: switch columns with rows
for (int i = 0; i < matrix.size(); i++) {
for (int j = i+1; j < matrix[0].size(); j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
//step2: switch columns
for (int left = 0, right = matrix.size()-1; left < right; left++, right--) {
for (int i = 0; i < matrix.size(); i++) {
int tmp = matrix[i][left];
matrix[i][left] = matrix[i][right];
matrix[i][right] = tmp;
}
}
return;
}
};
No comments:
Post a Comment