</br>
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?
</br>
Solution
Common way to rotate a image is to follow the step mentioned below.
Clockwise Rotate
1 2 3 7 8 9 7 4 1
4 5 6 => 4 5 6 => 8 5 2
7 8 9 1 2 3 9 6 3
first reverse up to down, then swap the symmetry
Anti-clockwise Rotate
1 2 3 3 2 1 3 6 9
4 5 6 => 6 5 4 => 2 5 8
7 8 9 9 8 7 1 4 7
first reverse left to right, then swap the symmetry
Therefore, in order to perform image rotation, we do not need to store matrix in additional space; instead, we can achieve this in-place by following steps above. First, perform reverse the matrix; then, swap the element symmetry.
Java
public class Solution {
public void rotate(int[][] matrix) {
int row = matrix.length;
int column = matrix[0].length;
for(int i=0;i<row/2;i++){
for(int j=0;j<column;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[row-1-i][j];
matrix[row-1-i][j] = temp;
}
}
for(int i=0;i<row;i++){
for(int j=i;j<column;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
}