[Leedcode 48] 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?

In order to fulfill the follow up requirement, i.e. In-place, we should utilize a temporary int variable and switch the V  Alues in the matrix. Coming back to our problem, rotating a matrix can is divided into steps and each step responses to rotating specific layer  of the Matrix. For example, when n=6 there is N/2 = 3 steps from outside layers to inside layers.

 Public classSolution {/*Public void Rotate (int[][] matrix) {//The subject must pay attention to the boundary. Each layer of the loop represents the inversion of one layer (from the outside to the inner loop), with a total of len/2 layers.                Note the value of J,j>=i,j<len-i-1;        int len=matrix.length;                for (int i=0;i<len/2;i++) {for (int j=i;j<len-i-1;j++) {int temp=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-I-1];                            Matrix[j][len-i-1]=temp; }         }    }*/             Public voidRotateint[] matrix) {        //another solution to the subject, first flipped along the horizontal midline, and then along the main diagonal, flipped once, and finally able to achieve a clockwise rotation of 90 degrees//or, first flip along the diagonal, and then flip it one time along the horizontal midline.         intlen=matrix.length; intI=0; intJ=0;  for(; i<len/2;i++){             for(j=0;j<len;j++){                inttemp=Matrix[i][j]; MATRIX[I][J]=matrix[len-1-i]                [j]; Matrix[len-1-i][j]=temp; }        }         for(i=0;i<len;i++){             for(j=i+1;j<len;j++){                inttemp=Matrix[i][j]; MATRIX[I][J]=Matrix[j][i]; Matrix[j][i]=temp; }        }             }}

[Leedcode 48] Rotate Image

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.