[Leetcode] Rotate Image @ Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.