DAY21:leetcode #48 Rotate Image

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?

Subscribe to see which companies asked this question

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        n_len = len(matrix)
        flag_odd = n_len % 2 == 1
        for i in range((n_len + 1) / 2):
            flag_i_mid = i == (n_len + 1) / 2 - 1
            for j in range(i if flag_odd and flag_i_mid else 0, (n_len + 1) / 2):
                i_temp = i
                j_temp = j
                temp1 = matrix[i][j]
                temp2 = 0
                for xx in range(4):
                    temp2 = matrix[j_temp][n_len - i_temp - 1]
                    matrix[j_temp][n_len - i_temp - 1] = temp1
                    i_temp, j_temp = (j_temp) , (n_len - i_temp - 1)
                    temp1 = temp2


这个题的思路是遍历矩阵左上角元素(篮框),将每一个左上角元素的付给对应的下一个元素(红色箭头),转一圈(4次赋值)。


有种特殊情况:

当n为奇数时,红框内的元素在遍历中已被赋值过,不需要对它们再进行一次遍历。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值