[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; } } }}