leetcode——Rotate Image

本文介绍了一种在原地将n x n的二维矩阵顺时针旋转90度的方法。通过观察不同尺寸矩阵的旋转规律,总结出矩阵中每个元素的变换规则,并给出AC代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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?

思路:

首先,要求原地调整,那么需要寻找变换规律。举个例子:

对于3x3的矩阵,如顺时针调整(0,0)->(0,2)->(2,2)->(2,0)

对于4x4的矩阵,如顺时针调整(0,0)->(0,3)->(3,3)->(3,0);(0,1)->(1,3)->(3,2)->(2,0);(0,2)->(2,3)->(3,1)->(1,0).

转换传递规律:对于一个nxn矩阵来说,(a,b)->(b,n-1 - a),并且该链式传递转换有四部。

当矩阵最外一层转换完之后,向内进发一层,继续转换。

如下代码中:for循环结束时,是该层一圈的所有点转换完成。然后修改n和start,使得开始点向内一圈再次进行传递转换。


AC代码:

public void rotate(int[][] matrix) {
        if(matrix==null || matrix.length==0)
            return;
        int n = matrix.length;
        int start = 0;
        while(n>1){

            for(int i=start;i<matrix.length-1-start;i++){
                int tmp = matrix[start][i];
                matrix[start][i] = matrix[matrix.length-1 - i][start];
                matrix[matrix.length-1-i][start] = matrix[matrix.length-1 - start][matrix.length-1-i];
                matrix[matrix.length-1 - start][matrix.length-1-i] = matrix[i][matrix.length-1-start];
                matrix[i][matrix.length-1-start]= tmp;
            }
            n-=2;
            start++;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值