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:
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
void rotate(vector<vector<int>>& m) {
reverse(m.begin(), m.end());
int rows = m.size(), cols = m[0].size();
if(rows == 0) return;
for(int i = 0; i < rows - 1; i++ )
for(int j = i + 1; j < cols; j++)
swap(m[i][j], m[j][i]);
}
};