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?
Subscribe to see which companies asked this question
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int rows = matrix.size(), cols = matrix[0].size();
int uprow = 0, downrow = rows-1, leftcol = 0, rightcol = cols-1;
for(; uprow < downrow; uprow++, downrow--) {
int ax = uprow, ay = leftcol;
int bx = uprow, by = rightcol;
int cx = downrow, cy = leftcol;
int dx = downrow, dy = rightcol;
int cnt = downrow-uprow;
while(cnt--) {
int temp = matrix[bx][by];
matrix[bx][by] = matrix[ax][ay];
matrix[ax][ay] = matrix[cx][cy];
matrix[cx][cy] = matrix[dx][dy];
matrix[dx][dy] = temp;
ay+=1;
bx+= 1;
cx-=1;
dy-=1;
}
leftcol++;
rightcol--;
}
}
};