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?
Solution: 1. Rotate one-fourth of the image clockwise.
2. 123 -> 147 -> 741 (preferable)
456 258 852
789 369 963
1 class Solution { 2 public: 3 void rotate(vector<vector<int> > &matrix) { 4 rotate_2(matrix); 5 } 6 7 void rotate_1(vector<vector<int> > &matrix) { 8 int n = matrix.size(); 9 for (int i = 0; i < (n + 1) / 2; i++) 10 for (int j = 0; j < n / 2; j++) 11 rotateElement(matrix, i, j); 12 } 13 void rotateElement(vector<vector<int> > &matrix, int row, int col) 14 { 15 int temp = matrix[row][col]; 16 for (int i = 0; i < 3; i++) { 17 int c = row; 18 int r = matrix.size() - 1 - col; 19 matrix[row][col] = matrix[r][c]; 20 row = r; 21 col = c; 22 } 23 matrix[row][col] = temp; 24 } 25 26 void rotate_2(vector<vector<int> > &matrix) { 27 int N = matrix.size(); 28 for (int i = 0; i < N; ++i) 29 for (int j = i+1; j < N; ++j) 30 swap(matrix[i][j], matrix[j][i]); 31 for (int j = 0; j < N/2; ++j) 32 for (int i = 0; i < N; ++i) 33 swap(matrix[i][j], matrix[i][N-j-1]); 34 } 35 };