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?
First use a naive solution: create a new 2D matrix and use the following formula to copy the data.
result[j[n - i - 1] = marix[i][j];
public class Solution {
public void rotate(int[][] matrix) {
int[][] result = new int[matrix.length][matrix.length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
result[j][matrix.length - 1 - i] = matrix[i][j];
}
}
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix.length; j++){
matrix[i][j] = result[i][j];
}
}
}
}
Then consider the in-place case.
The formula becomes:
matrix[i][j] = matrix[n - 1 - j][i];
So the code is as follows:
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int[][] result = new int[n][n];
for(int i = 0; i < Math.ceil(((double) n) / 2); i++){
for(int j = 0; j < n / 2; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = temp;
}
}
}
}