Topic:
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?
Train of thought 1: Find correspondence, 90 degree flip is: Old ordinate--new horizontal axis New ordinate = the old horizontal axis inversion (maximum height-the old horizontal axis)
Public voidRotateint[] matrix) { int[] Temp =New int[Matrix.length] [Matrix[0].length]; for(inti = 0; i< matrix.length;i++){ for(intj = 0; j< matrix.length;j++) {Temp[j][matrix.length-1-i] =Matrix[i][j]; } } for(inti = 0; i< matrix.length;i++){ for(intj = 0; j< matrix.length;j++) {Matrix[i][j]=Temp[i][j]; } } }
Analysis: This method of problem-solving uses extra storage space!
Idea 2: Flip + fold
90 degree conversion = Flip (diagonal flip at any angle (apostrophe to flip): a[i][j] = a[j][i]) + fold (upside down or left/right flip): a[i][j] = a[i][length-1-j])
Note that 270 degrees is a similar idea.
Promotion: Flip 180 degrees = Flip (diagonal flip at any angle: a[i][j] = a[j][i])
Code:
Public voidRotateint[] matrix) { //to Flip for(inti = 0; i< matrix.length;i++){ for(intj = 0; J<i; j + +){ intTemp =Matrix[i][j]; MATRIX[I][J]=Matrix[j][i]; Matrix[j][i]=Temp; } } //Vertical Rollover for(inti = 0; i< matrix.length;i++){ for(intj = 0; j< matrix.length/2;j++){ intTemp = matrix[i][matrix.length-1-J]; Matrix[i][matrix.length-1-J] =Matrix[i][j]; MATRIX[I][J]=Temp; } } }
[Leetcode]: 48:rotate Image