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?
Idea: The matrix is considered to be surrounded by a layer of multiple squares. When you turn the side of the square, as long as the side of each number of the next to replace the good, four directions that is four times to replace each layer in turn.
Total number of layers = MATRIX.LENGTH/2, layer I starts from matrix[i][i] to matrix[i][n-1-1-i], note save temp = Matrix[i][i], ensure that the last substitution value is not overwritten, four substitutions in four directions per round
Public classS048 { Public voidRotateint[] matrix) { //find the rules and replace each of the four directions in each layer of the matrix in turn if(Matrix.length = = 1) return ; intLen =matrix.length; for(inti = 0;i<len/2;i++) { for(intj = i;j<len-1-i;j++) { inttemp =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-1-i]; Matrix[j][len-1-i] =temp; } } } Public Static voidMain (string[] args) {S048 s=NewS048 (); int[] nums= {{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}}; S.rotate (Nums); }}
Leetcode Rotate Image