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;iMethod 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