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?
1 class Solution { 2 public: 3 void rotate(vector<vector<int> > &matrix) { 4 int n = matrix.size(); 5 for(int i = 0; i < n / 2; ++i) { 6 for(int j = i; j < n - 1 - i; ++j){ 7 int t = matrix[i][j]; 8 matrix[i][j] = matrix[n - 1 - j][i]; 9 matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]; 10 matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; 11 matrix[j][n - 1 - i] = t; 12 } 13 } 14 } 15 };
由边缘至内部,一圈一圈地旋转。
另外的方法:先将图像沿副对角线翻转,再上下翻转。