Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

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.

基本思路为:
从最外圈到最内圈进行遍历交换,需要的圈数为 n2 ,在每圈元素的交换过程中,对于任意坐标数据(i,j),交换路径依次为(i,j) –> (j, n-i-1) –> (n-i-1, n-j-1) –> (n-j-1, i),每圈要进行的赋值的次数依次为5(n-1), 5(n-3), 5(n-5), … ,5次,因此时间复杂度为O( n2 ),由于每次交换实际只需要一个临时变量data保存当前数据,其他索引值仅仅只是为了程序的可读性进行设置,因此空间复杂度为O(1)。

class Solution {
public:
    void rotate_swap_four_data(vector<vector<int>>& matrix, int row, int col)
    {
        int order = matrix.size();
        int top_left_row = row;
        int top_left_col = col;
        int top_right_row = col;
        int top_right_col = order - row - 1;
        int bottom_right_row = order - row - 1;
        int bottom_right_col = order - col - 1;
        int bottom_left_row = order - col - 1;
        int bottom_left_col = row;
        int data = matrix[top_left_row][top_left_col];
        matrix[top_left_row][top_left_col] = matrix[bottom_left_row][bottom_left_col];
        matrix[bottom_left_row][bottom_left_col] = matrix[bottom_right_row][bottom_right_col];
        matrix[bottom_right_row][bottom_right_col] = matrix[top_right_row][top_right_col];
        matrix[top_right_row][top_right_col] = data;
    }

    void rotate(vector<vector<int>>& matrix) {
        int matrix_order = matrix.size();
        int round_count = matrix_order/2;
        for(int round = 0; round < round_count; round++)
        {
            int start_pos = round;
            int end_pos = matrix_order - round - 1;
            for(int col = start_pos; col < end_pos; col++)
            {
                rotate_swap_four_data(matrix, start_pos, col);
            }
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值