[LeetCode] 48. Rotate Image



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

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?



Solution

Common way to rotate a image is to follow the step mentioned below.

Clockwise Rotate
  1 2 3     7 8 9     7 4 1
  4 5 6  => 4 5 6  => 8 5 2
  7 8 9     1 2 3     9 6 3

first reverse up to down, then swap the symmetry 
Anti-clockwise Rotate
  1 2 3     3 2 1     3 6 9
  4 5 6  => 6 5 4  => 2 5 8
  7 8 9     9 8 7     1 4 7

first reverse left to right, then swap the symmetry

Therefore, in order to perform image rotation, we do not need to store matrix in additional space; instead, we can achieve this in-place by following steps above. First, perform reverse the matrix; then, swap the element symmetry.

Java

public class Solution {
    public void rotate(int[][] matrix) {
    
        int row = matrix.length;
        int column = matrix[0].length;
        
        for(int i=0;i

你可能感兴趣的:([LeetCode] 48. Rotate Image)