Rotate the image
Given an n × n 2D matrix representing an image.
Rotate the image 90 degrees clockwise.
illustrate
// You have to rotate the image in place, which means you need to modify the input 2D matrix directly. Please don't use another matrix to rotate the image.
Example
Given matrix = [ [ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ] ], rotate the input matrix in place : [ [ 7 , 4 , 1 ] , [ 8 , 5 , 2 ], [ 9 , 6 , 3 ] ] Given matrix = [ [ 5 , 1 , 9 , 11 ], [ 2 , 4 , 8 , 10 ], [ 13 , 3 , 6 , 7 ], [ 15 , 14 , 12 , 16 ] ], rotate the input matrix in place : [ [ 15 , 13 , 2 , 5 ], [ 14 , 3 , 4 , 1 ], [12, 6, 8, 9], [16, 7,10,11] ]
ideas
Coordinate rotation ( clockwise ) 90 ° (equivalent to 270° counterclockwise): a [ i ][ j ] = b [ j ][ n - i - 1 ]; // Transpose the rows and columns of the matrix to create a new matrix : b [ i ][ j ] = a [ j ][ i ]; Calculate the transposed matrix of the original matrix, and invert each row of the transposed matrix to obtain a matrix rotated by 90°
code
class Solution { public void rotate(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int length = matrix.length; for (int i = 0; i < length / 2; i++) { for (int j = 0; j < (length + 1) / 2; j++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[length - j - 1][i]; matrix[length - j - 1][i] = matrix[length - i - 1][length - j - 1]; matrix[length - i - 1][length - j - 1] = matrix[j][length - i - 1]; matrix[j][length - i - 1] = tmp; } } } }