48、Rotate Image

本文介绍了一个算法,用于将n x n的二维矩阵表示的图像顺时针旋转90度,并探讨了如何在不使用额外空间的情况下实现这一操作。

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

ou 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?


 void rotate(vector<vector<int> > &matrix) {
        //顺时针旋转图片,主要是找规律,二维矩阵, (i, j)元素最后到位置(j,n - i - 1),in-place就地进行变换是说不能使用额外空间吗?
        int len = matrix.size();
        int count = len / 2;
        for (int i = 0; i < count; ++i)
        {
            int end = len - i - 1;//注意end = len - i - 1;之前忘记多-1,老是出错
            int row, col, temp, tt;
            for (int j = i; j < end; ++j)
            {
                row = i;
                col = j;
                //下面的代码可以用循环进行优化,自己懒得优化了
                temp = matrix[row][col];
                swap(temp, matrix[col][len - row - 1]);
                tt = col;//0
                col = len - row - 1;//1
                row = tt;//0
                swap(temp, matrix[col][len-row - 1]);
                tt = col;//1
                col = len - row - 1;//1
                row = tt;//1
                swap(temp, matrix[col][len - row - 1]);
                matrix[i][j] = temp;
            }
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值