[LeetCode] [Java] Rotate Image

Source: Internet
Author: User
Tags rotate image

[LeetCode] [Java] Rotate Image
Question:

 

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise ).

Follow up:
Cocould you do this in-place?

Question:

A two-dimensional matrix of n x n is given to represent an image.

Rotate the image 90 degrees (clockwise)

Can you complete it on the original matrix?

Algorithm analysis:

Method 1:

The space complexity is high, and additional space is used to copy the original matrix. But it is better to understand

Find the rule: matrix [j] [l-i-1] = temmatrix [I] [j];

Temmatrix stores the original matrix.

Method 2:

Reference blog http://pisxw.com/algorithm/Rotate-Image.html

The basic idea is to divide the image into rows/two layers, and then rotate them layer by layer. Each layer has four columns: top, bottom, left, and right. The goal is to put the upper column in the right column and the right column in the following column, put the following in the left column, put the left column back in the upper column, and save a temporary variable in the middle.

AC code:

Method 1:

 

Public class Solution {public void rotate (int [] [] matrix) {int h = matrix. length; int l = matrix [0]. length; int tem [] [] = new int [h] [l]; for (int I = 0; I
 
  Method 2:
  
public class Solution {    public void rotate(int[][] matrix) {        if(matrix==null)            return;        int n=matrix.length-1;        for (int i = 0; i <= n/2; ++i)            {                for (int j = i; j < n-i; ++j)                {                    int tmp = matrix[i][j];                    matrix[i][j] = matrix[n-j][i];                    matrix[n-j][i] = matrix[n-i][n-j];                    matrix[n-i][n-j] = matrix[j][n-i];                    matrix[j][n-i] = tmp;                }            }        }}


 

 

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.