[Leetcode] [Java] Rotate Image

Source: Internet
Author: User

Title:

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?

Test Instructions:

a two-dimensional matrix of n x n is given to represent a pair of images.

Rotate the image 90 degrees (clockwise)

Can you finish it on the original matrix?

Algorithm Analysis:

Method One:

The space complexity is high, opening up additional space to replicate the original matrix. But it's better to understand

Find the law can: matrix[j][l-i-1]=temmatrix[i][j];

Temmatrix, the original matrix is stored here.

Method Two:

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

The basic idea is to divide the picture into rows/2 layers, then a layer of rotation, each layer has up and down four columns, and then the goal is to put the list to the right column, the right column to the following, put the following to the left column, left column back to the above, save a temporary variable in the middle.


AC Code:

Method One:

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 Two:
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;}}}}        


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

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