Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
Each time rotate 4 pixles (i, j), (j, n-i), (n-i, n-j) and (n-j, i). We iterate i and j in a upper-left quater square. However, when N is odd, the four quater square would have overlap, so some modification should be made, and the square changes to a rectangle.
/*Implemention problem, we first need to know the scale of N, we assume int is Ok to restore it, then according to the problem, each pixel is 4 bytes, then int is enough, we also assume that we rotate the matrix anticlockwise. It is easy to show that the four corresponding position in the matrix is (i, j), (j, n-i), (n-i, n-j) and (n-j, i). We just need to iterate the upper-left quater of the matrix, but be careful with odd N, there exist overlap during the rotation if we apply the same method like even N */ public class RotateMatrix { public void rotateMatrix(int[][] matrix) { int n = matrix.length; if(n == 0) return ; int p = 0, q = 0; if(n%2 == 0) { p = n/2; q = n/2;} else {p = (n+1)/2; q = n/2;} for(int i = 0; i < p; i++) { for(int j = 0; j < q; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][n-i-1]; matrix[j][n-i-1] = matrix[n-i-1][n-j-1]; matrix[n-i-1][n-j-1] = matrix[n-j-1][i]; matrix[n-j-1][i] = temp; } } } public void print(int[][] matrix) { int n = matrix.length; if(n == 0) return; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(""); } } public static void main(String[] args) { RotateMatrix rm = new RotateMatrix(); int[][] matrix1 = {{1}}; int[][] matrix2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int[][] matrix3 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int[][] matrix4 = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}; rm.rotateMatrix(matrix1); rm.print(matrix1); rm.rotateMatrix(matrix2); rm.print(matrix2); rm.rotateMatrix(matrix3); rm.print(matrix3); rm.rotateMatrix(matrix4); rm.print(matrix4); } }