题目:
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?
分析与解答:
先沿对角线反转,再沿中线上下旋转。
class Solution { public: void rotate(vector<vector<int> > &matrix) { int size = matrix.size(); for (int i = 0; i < size; ++i){ for (int j = 0; j < size - i - 1; ++j){ swap(matrix[i][j], matrix[size - j - 1][size - i - 1]); } } for (int i = 0; i < size / 2; ++i){ for (int j = 0; j < size; ++j){ swap(matrix[i][j], matrix[size - i - 1][j]); } } } };