"Leetcode" "Python puzzle" Rotate Image

Source: Internet
Author: User
Tags rotate image

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?

My solution is very concise, using a line of code, is the given matrix re-integration, generated a new matrix return, so not in-place solution, but the advantages are very concise, pleasing!

Class solution:    # @param Matrix, a list of lists of integers    # @return A list of lists of integers    def rotate ( Self, matrix):        return Map (lambda X:map (lambda y:y.pop (0), matrix[::-1]), Range (len (matrix)))

Share a look at the very handsome solution, this algorithm is In-place

#include <algorithm>class Solution {public:    void rotate (vector<vector<int> > &matrix)     {        reverse (matrix.begin (), Matrix.end ());        for (unsigned i = 0; i < matrix.size (), ++i) for            (unsigned j = i+1; J < Matrix[i].size (); ++j)                swap (matrix[ I][J], matrix[j][i]);}    ;

At first glance, it is very difficult to understand, just like the diagonal of the matrix to exchange the pixels on both sides. Not really. A very critical step is the reverse () function, which flips the matrix. If you write a nxn matrix on a piece of paper (which I write down to understand anyway), reverse is the equivalent of flipping the paper over, and not flipping along the long side, but flipping along the short side (that is, not flipping through the book, but flipping from the bottom upwards), The bottom line is naturally the topmost row after flipping.

The second step is to swap the elements on both sides of the diagonal, which is also a flip, this time the flip is more complicated, is a flip along the diagonal of the matrix (it can be said along the diagonal of the paper)

At this point you will find that this is the paper rotated 90 degrees clockwise.

"Leetcode" "Python puzzle" Rotate Image

Related Article

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.