DAY21:leetcode #48 Rotate Image

来源:互联网 发布:mac ppt使用教程 编辑:程序博客网 时间:2024/06/07 17:36

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为奇数时,红框内的元素在遍历中已被赋值过,不需要对它们再进行一次遍历。


0 0
原创粉丝点击