Leetcode-rotate Image

Source: Internet
Author: User
Tags rotate image

You are givenNXN2D matrix representing an image.

Rotate the image by 90 degrees (clockwise ).

Follow up:
Cocould you do this in-place

 

The N * n matrix rotates 90 degrees clockwise. Law a [I] [J] --> A [J] [n-I]

Idea 1. Copy Data row by row according to the rule. A new two-dimensional array needs to be created, with a slightly higher space complexity.

2. Replace the elements and target positions one by one according to the rule. It is found that the coordinates will return to the starting position every four times.

Take the 4*4 matrix as an example. A [0] [0] --> A [0] [3] --> A [3] [3] --> A [3] [0] ---> A [0] [0]

Each row is traversed (n-1), and the square composed of the elements in the outermost ring has reached the goal.

Scale down the square and replace it by line.

 1 public class Solution { 2         public void rotate(int[][] matrix) { 3             if(matrix == null ||matrix.length <= 1){ 4                 return; 5             } 6             int n = matrix.length; 7             int rectangleLen = n; 8             int row = 0; 9             while(rectangleLen >=2){10                 for(int i =row;i<= n-2 - row ;i++){11                     rotateRectangle(matrix,n,row,i);    12                 }13                 rectangleLen-= 2;14                 row ++;15             }16         }17         18         public void rotateRectangle(int[][] matrix,int n,int x_pos,int y_pos){19             int temp = matrix[x_pos][y_pos];20             int target  = 0;21             int temp_pos = 0;22             for(int i=0;i<4;i++){23                 target = temp;24                 //target position25                 temp_pos = x_pos;26                 x_pos = y_pos;27                 y_pos = n - 1 - temp_pos;28                 temp  = matrix[x_pos][y_pos];29                 //replace30                 matrix[x_pos][y_pos] = target; 31             }32         }33 }

 

Leetcode-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.