当前位置 博文首页 > 文章内容

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

    作者: 栏目:未分类 时间:2020-11-02 9:00:55

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



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