You are given an n x n 2D matrix representing an image. Rotate the image by 90
degrees (clockwise).
Example
Given a matrix
[
[1,2],
[3,4]
]
rotate it by 90 degrees (clockwise), return
[
[3,1],
[4,2]
]
Challenge
Tags
Expand
Do it in-place.
Related Problems Expand
class Solution {
public:
/**
* @param matrix: A list of lists of integers
* @return: Void
*/
void rotate(vector<vector<int> > &matrix) {
// write your code here
if (matrix.size() == 0 || matrix.size() == 1)
return;
int layer = matrix.size()/2;
for (int layer=0; layer<matrix.size()/2; layer++)
{
int first = layer;
int last = matrix.size()-1-layer;
for (int i=first; i<last; i++)
{
int offset = i-first;
int top = matrix[first][i];
matrix[first][i] = matrix[last-offset][first];
matrix[last-offset][first] = matrix[last][last-offset];
matrix[last][last-offset] = matrix[i][last];
matrix[i][last] = top;
}
}
}
};