LeetCode代码分析——48. Rotate Image(数组旋转)

题目描述

You are given an n x n 2D matrix representing an image.
给定一个n*n的二维数组,表示一个图片
Rotate the image by 90 degrees (clockwise).
将图片顺时针旋转90度

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
必须原地旋转图片,也就是说你必须直接修改输入的二维数组而不可以创建另一个二维数组来做旋转。

Example 1:

Given **input matrix** = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix **in-place** such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Example 2:

Given **input matrix** =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

rotate the input matrix **in-place** such that it becomes:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

思路分析

本题可以直接对每个数进行旋转,也可以利用矩阵的特性进行翻转等操作来实现(详见https://www.cnblogs.com/93scarlett/p/6362085.html),本文采用直观好理解的直接旋转来实现。
矩阵每个点的旋转如图所示,根据图中规律和坐标的规律可以看出,每次的旋转都会让坐标转置(横纵坐标对换)然后关于y轴对称过去。以后考虑矩阵规律的问题时也要考虑是否转置一下就可以找到规律了

矩阵旋转的过程

因此,我们可以将旋转过程中每个90度的位置作为一个点,旋转一圈是4个点,可以将这4个点作为一组进行旋转。因此只需要遍历全部矩阵的1/4就可以完成全部的旋转,我们选定如图所示的三角形区域进行旋转。

代码实现

public class Solution {

    /**
     *
     * 21 / 21 test cases passed.
     *  Status: Accepted
     *  Runtime: 4 ms
     *
     * @param matrix
     */
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for (int i = 0; i < n / 2; i++) {
            for (int j = i; j < n - 1 - i; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n - 1 - j][i];
                matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
                matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
                matrix[j][n - 1 - i] = temp;
            }
        }
    }

}

你可能感兴趣的:(LeetCode代码分析——48. Rotate Image(数组旋转))