You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note: You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13
Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ],
rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ]
classSolution { public: voidrotate(vector<vector<int> > &matrix){ int temp = 0, row = 0, col = 0, tmp = 0; for (int i = 0; i < matrix.size() / 2; ++i) { for (int j = i; j < matrix.size() - i - 1; ++j) { row = i; col = j; for (int k = 0; k < 5; ++k) { tmp = matrix[row][col]; matrix[row][col] = temp; temp = row; row = col; col = matrix.size() - 1 - temp; temp = tmp; } } } } };
/* n represents the matrix's dimension row represents the row of the present position col represents the column of the present position Actually, the transform function can be written as: new_row = col new_col = n - row - 1 Example: 1 2 3 7 2 1 7 4 1 4 5 6 -> 4 5 6 -> 8 5 2 7 8 9 9 8 3 9 6 3 */