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?
Without followup, we can directly create a new n x n 2D matrix, then format the value of which as the rotation of the original matrix.
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int[][] rotatedMatrix = new int[n][n];
// Construct rotated matrix
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
rotatedMatrix[j][n-1-i] = matrix[i][j];
}
}
// Reformat override original matrix
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
matrix[i][j] = rotatedMatrix[i][j];
}
}
}
}
In order to fulfill the follow up requirement, i.e. in-place, we should utilize a temporary int variable and switch the values in the matrix. Coming back to our problem, rotating a matrix can be divided into steps and each step responses to rotating specific layer of the matrix. For example, when n=6 there are n/2 = 3 steps from outside layers to inside layers.
In each step, we can use an iteration to switch the values.
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
if (n==0 || n==1) return;
for(int i=0; i<n/2; i++){ // i layers
for(int j=i; j<n-i-1; j++){ // rotate for ith layer
int temp = matrix[i][j];
matrix[i][j] = matrix[n-j-1][i];
matrix[n-j-1][i] = matrix[n-i-1][n-j-1];
matrix[n-i-1][n-j-1] = matrix[j][n-i-1];
matrix[j][n-i-1] = temp;
}
}
return;
}
}
A key point of this approach is the value range of variable j, it changes in each step according to the size of the layer.