Loading

[LeetCode] 48. Rotate Image(旋转图片)

Description

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
给你一个 n x n 的二维矩阵 matrix 表示一张图片,将该图片顺时针旋转 90°。

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.
你必须原地完成旋转操作,也就是说,你必须直接修改原先的二维数组。不要另外分配二维数组完成旋转。

Examples

Example 1

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2

Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Example 3

Input: matrix = [[1]]
Output: [[1]]

Example 4

Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

Constraints

  • matrix.length == n

  • matrix[i].length == n

  • 1 <= n <= 20

  • -1000 <= matrix[i][j] <= 1000

Solution

一开始一直在想一步到位的骚操作,最后没想出来,一翻 discussion 后恍然大悟,一步做不出来,为什么不分成两步做呢?

顺时针 90° 旋转一张图片,需要以下两步(假设图片中心位于直角坐标原点):

  1. 整张图片以 x 轴翻转

  2. 整张图片以主对角线(\(y = -x\))进行翻转

代码如下:

class Solution {
    fun rotate(matrix: Array<IntArray>): Unit {
        flipVertical(matrix)
        flipDiagonal(matrix)
    }

    private fun flipDiagonal(matrix: Array<IntArray>) {
        for (i in matrix.indices) {
            for (j in 0 until i) {
                val t = matrix[i][j]
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = t
            }
        }
    }

    private fun flipVertical(matrix: Array<IntArray>) {
        var i = 0
        var j = matrix.lastIndex

        while (i < j) {
            val t = matrix[i]
            matrix[i] = matrix[j]
            matrix[j] = t

            i++
            j--
        }
    }
}
posted @ 2020-11-02 08:55  Zhongju.copy()  阅读(83)  评论(0编辑  收藏  举报