Leetcode: rotating an image [48]

Source: Internet
Author: User

Leetcode: rotating an image [48] Title Description

GivenN×NThe two-dimensional matrix of represents an image.

Rotate the image 90 degrees clockwise.

Note:

You must rotate the image in the original position, which means you need to directly modify the input two-dimensional matrix. Do not use another matrix to rotate the image.

Example 1:

 
Given matrix = [[, 3], [, 6], [, 9], rotate the input matrix in the same place to [[, 4, 1], [8, 5, 2], [9, 6, 3]

Example 2:

 
Given matrix = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16], rotate the input matrix to [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]
Question Analysis

The most stupid method is simulation. However, in a short period of time, it is impossible to accurately extract all the simulated boundary judgment conditions. The code is redundant and cannot be optimized.

What should we do? We can seeThe implicit condition is that the given matrix must be square.. Because we cannot create an array, if the original array is a rectangle, we cannot represent the result in any case.

So what then? WeFirst, transpose the rows and columns.!

Next, wePerform image transformation on the central axis, swap (ARR [I] [J], arr [I] [matrix. length-1-j])

At last, we should think about why this is okay?

Java question
Public void rotate (INT [] [] matrix) {for (INT I = 0; I <matrix. length; I ++) {for (Int J = I; j <matrix [0]. length; j ++) {int temp = 0; temp = matrix [I] [J]; matrix [I] [J] = matrix [J] [I]; matrix [J] [I] = temp; }}for (INT I = 0; I <matrix. length; I ++) {for (Int J = 0; j <matrix. length/2; j ++) {int temp = 0; temp = matrix [I] [J]; matrix [I] [J] = matrix [I] [matrix. length-1-j]; matrix [I] [matrix. length-1-j] = temp ;}}}

 

Leetcode: rotating an image [48]

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.