leetcode(21)-旋转矩阵

时间:2020-01-09
本文章向大家介绍leetcode(21)-旋转矩阵,主要包括leetcode(21)-旋转矩阵使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

给定一个 n × n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

说明:

你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-image
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

我的解法

像剥洋葱一样,一圈一圈旋转,每一圈,分为四个元素的置换。算出来四个坐标就行

class Solution:
    def rotate(self, matrix) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        length = len(matrix)
        for i in range(length//2):  # 有多少圈
            nums = (length-i*2)-1
            edge = length-i*2
            for j in range(nums): # 一圈有多少个*4的交换
                begin_x = i
                begin_y = i+j
                n_1 = (begin_x,begin_y)
                n_2 = (i+j,i+edge-1)
                n_3 = (begin_x+edge-1,n_2[1]-j)
                n_4 = (n_3[0]-j,i)
                matrix[n_1[0]][n_1[1]],matrix[n_2[0]][n_2[1]],matrix[n_3[0]][n_3[1]],matrix[n_4[0]][n_4[1]] = matrix[n_4[0]][n_4[1]],matrix[n_1[0]][n_1[1]],matrix[n_2[0]][n_2[1]],matrix[n_3[0]][n_3[1]]

原文地址:https://www.cnblogs.com/Lzqayx/p/12172228.html