Leetcode: rotating an image [48] Title Description
GivenN×NThe two-dimensional matrix of represents an image.
Rotate the image 90 degrees clockwise.
Note:
You must rotate the image in the original position, which means you need to directly modify the input two-dimensional matrix. Do not use another matrix to rotate the image.
Example 1:
Given matrix = [[, 3], [, 6], [, 9], rotate the input matrix in the same place to [[, 4, 1], [8, 5, 2], [9, 6, 3]
Example 2:
Given matrix = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16], rotate the input matrix to [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]
Question Analysis
The most stupid method is simulation. However, in a short period of time, it is impossible to accurately extract all the simulated boundary judgment conditions. The code is redundant and cannot be optimized.
What should we do? We can seeThe implicit condition is that the given matrix must be square.. Because we cannot create an array, if the original array is a rectangle, we cannot represent the result in any case.
So what then? WeFirst, transpose the rows and columns.!
Next, wePerform image transformation on the central axis, swap (ARR [I] [J], arr [I] [matrix. length-1-j])
At last, we should think about why this is okay?
Java question
Public void rotate (INT [] [] matrix) {for (INT I = 0; I <matrix. length; I ++) {for (Int J = I; j <matrix [0]. length; j ++) {int temp = 0; temp = matrix [I] [J]; matrix [I] [J] = matrix [J] [I]; matrix [J] [I] = temp; }}for (INT I = 0; I <matrix. length; I ++) {for (Int J = 0; j <matrix. length/2; j ++) {int temp = 0; temp = matrix [I] [J]; matrix [I] [J] = matrix [I] [matrix. length-1-j]; matrix [I] [matrix. length-1-j] = temp ;}}}
Leetcode: rotating an image [48]