Problem:
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?
Analysis:
Solutions:
C++:
void SwapClockwise(int &lu, int &lb, int &ru, int &rb)
{
swap(lu, ru);
swap(lb, rb);
swap(lu, rb);
}
void rotate(vector<vector<int> > &matrix) {
int n = matrix.size();
if(n <= 1)
return;
for(int upper = 0, lower = n - 1; upper < lower; ++upper, --lower) {
for(int start = upper; start < lower; ++start) {
int &lu = matrix[upper][start];
int &ru = matrix[start][lower];
int &lb = matrix[n - 1 - start][upper];
int &rb = matrix[lower][n - 1 - start];
SwapClockwise(lu, lb, ru, rb);
}
}
}
Java
:
Python: