You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise) in place.
[1,2,3]
[4,5,6]
[7,8,9]
4(1,0) <- 8(2,1) i is flipped
8(2,1) <- 6(1,2) i is flipped
6(1,2) <- 2(0,1) i is flipped
2(0,1) <- 4(1,0) i is flipped
j2 = i1
i2 = n-1-j1
public void rotate(int[][] matrix) {
int n=matrix.length;
for(int i=0;i<n/2;i++) {
for(int j=0;j<(n+1)/2;j++) {
//store top left
int temp = matrix[i][j];
//set top left from bottom left - because j will increase in each loop, so move element from bottom left, element above bottom left etc.
matrix[i][j] = matrix[n-1-j][i];
//set bottom left from bottom right
matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
//set bottom right from top right
matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
//set top right from top left
matrix[j][n-1-i] = temp;
}
}
}