[Leetcode]: 48:rotate Image

Source: Internet
Author: User
Tags rotate image

Topic:

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?

Train of thought 1: Find correspondence, 90 degree flip is: Old ordinate--new horizontal axis New ordinate = the old horizontal axis inversion (maximum height-the old horizontal axis)

     Public voidRotateint[] matrix) {        int[] Temp =New int[Matrix.length] [Matrix[0].length];  for(inti = 0; i< matrix.length;i++){             for(intj = 0; j< matrix.length;j++) {Temp[j][matrix.length-1-i] =Matrix[i][j]; }        }                 for(inti = 0; i< matrix.length;i++){             for(intj = 0; j< matrix.length;j++) {Matrix[i][j]=Temp[i][j]; }        }    }

Analysis: This method of problem-solving uses extra storage space!

Idea 2: Flip + fold

90 degree conversion = Flip (diagonal flip at any angle (apostrophe to flip): a[i][j] = a[j][i]) + fold (upside down or left/right flip): a[i][j] = a[i][length-1-j])

Note that 270 degrees is a similar idea.

Promotion: Flip 180 degrees = Flip (diagonal flip at any angle: a[i][j] = a[j][i])

Code:

     Public voidRotateint[] matrix) {                //to Flip         for(inti = 0; i< matrix.length;i++){             for(intj = 0; J<i; j + +){                intTemp =Matrix[i][j]; MATRIX[I][J]=Matrix[j][i]; Matrix[j][i]=Temp; }        }                //Vertical Rollover         for(inti = 0; i< matrix.length;i++){             for(intj = 0; j< matrix.length/2;j++){                intTemp = matrix[i][matrix.length-1-J]; Matrix[i][matrix.length-1-J] =Matrix[i][j]; MATRIX[I][J]=Temp; }        }    }

[Leetcode]: 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.