Test instructions
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?
Problem-Solving ideas 1: First flip along the diagonal, and then flip along the horizontal midline, you can get the required matrix. Time complexity O (n^2), Space complexity O (1)
classSolution:#@param Matrix, a list of lists of integers #@return A list of lists of integers defrotate (self, matrix):#idea 1, Time complexity O (n^2), Space complexity O (1)n =len (Matrix) forIinchrange (n): forJinchRange (N-i):#invert diagonally along the diagonalMATRIX[I][J], matrix[n-1-j][n-1-i] = matrix[n-1-j][n-1-i], Matrix[i][j] forIinchRange (N/2):#reverse along the horizontal midline forJinchrange (N): matrix[i][j], Matrix[n-1-I][J] = matrix[n-1-i] [j], Matrix[i][j]returnMatrix
Solution 2: First transpose the Matrix, and then flip each line of the matrix, you can get the required matrix.
Reference:http://www.cnblogs.com/zuoyuan/p/3772978.html
classSolution:#@param Matrix, a list of lists of integers #@return A list of lists of integers defrotate (self, matrix): N=len (Matrix) forIinchrange (n): forJinchRange (i+1, N): Matrix[i][j], Matrix[j][i]= Matrix[j][i], matrix[i][j]#Transpose The matrix first forIinchrange (N): Matrix[i].reverse ()#then flip each line of the matrix returnMatrix
[Leetcode] Rotate Image @ Python