You are given a n x n 2D matrix representing an image.
Rotate the image by degrees (clockwise).
Follow up:
Could do this in-place?
In order to fulfill the follow up requirement, i.e. In-place, we should utilize a temporary int variable and switch the V Alues in the matrix. Coming back to our problem, rotating a matrix can is divided into steps and each step responses to rotating specific layer of the Matrix. For example, when n=6 there is N/2 = 3 steps from outside layers to inside layers.
Public classSolution {/*Public void Rotate (int[][] matrix) {//The subject must pay attention to the boundary. Each layer of the loop represents the inversion of one layer (from the outside to the inner loop), with a total of len/2 layers. Note the value of J,j>=i,j<len-i-1; int len=matrix.length; for (int i=0;i<len/2;i++) {for (int j=i;j<len-i-1;j++) {int temp=matrix[i][j]; Matrix[i][j]=matrix[len-1-j][i]; MATRIX[LEN-1-J][I]=MATRIX[LEN-1-I][LEN-1-J]; MATRIX[LEN-1-I][LEN-1-J]=MATRIX[J][LEN-I-1]; Matrix[j][len-i-1]=temp; } } }*/ Public voidRotateint[] matrix) { //another solution to the subject, first flipped along the horizontal midline, and then along the main diagonal, flipped once, and finally able to achieve a clockwise rotation of 90 degrees//or, first flip along the diagonal, and then flip it one time along the horizontal midline. intlen=matrix.length; intI=0; intJ=0; for(; i<len/2;i++){ for(j=0;j<len;j++){ inttemp=Matrix[i][j]; MATRIX[I][J]=matrix[len-1-i] [j]; Matrix[len-1-i][j]=temp; } } for(i=0;i<len;i++){ for(j=i+1;j<len;j++){ inttemp=Matrix[i][j]; MATRIX[I][J]=Matrix[j][i]; Matrix[j][i]=temp; } } }}
[Leedcode 48] Rotate Image