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?
Could you do this in-place?
Rotate layer by layer. In each layer move 4 elements in the same time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void rotate(vector<vector<int> >& matrix) { | |
int layers=ceil(matrix.size()/2); | |
int N=matrix.size(); | |
int n=N; | |
for(int i=layers; i>=1; i--){ | |
int r=layers-i; | |
for(int j=r; j<r+n-1; j++){ | |
int c=j; | |
int u=matrix[r][c]; | |
int rt=matrix[c][N-layers+i-1]; | |
int d=matrix[N-layers+i-1][N-c-1]; | |
int l=matrix[N-c-1][layers-i]; | |
matrix[c][N-layers+i-1]=u; | |
matrix[N-layers+i-1][N-c-1]=rt; | |
matrix[N-c-1][layers-i]=d; | |
matrix[r][c]=l; | |
} | |
n=n-2; // get to next layers inside | |
} | |
} | |
}; |
No comments:
Post a Comment