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?
More intuitive solution.
With up left index and bottom right index layer by layer
Each outer iteration will rotate one layer and after that upleft index -- and bottomright index++, we proceed to process next layer.
With up left index and bottom right index layer by layer
Each outer iteration will rotate one layer and after that upleft index -- and bottomright index++, we proceed to process next layer.
public void rotate(int[][] matrix) {
int n=matrix.length;
int upleft=0;
int bottomright=n-1;
while(upleft<bottomright){
for(int j=upleft;j<bottomright;j++){
int temp=matrix[upleft][j];
matrix[upleft][j]=matrix[n-j-1][upleft];
matrix[n-j-1][upleft]=matrix[bottomright][n-j-1];
matrix[bottomright][n-j-1]=matrix[j][bottomright];
matrix[j][bottomright]=temp;
}
upleft++;
bottomright--;
}
}
No comments:
Post a Comment