LeetCode Rotate Image

LeetCode解题之Rotate Image


原题

将一个矩阵顺时针旋转90度。

注意点:

  • 最好不要申请额外空间

样例:

输入: matrix = [[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]

输出: [[7, 8, 1],
[6, 9, 2],
[5, 4, 3]]

解题思路

假设能够申请额外空间,哪怕一个暂时的变量,那仅仅要找一下规律还是非常easy实现的。但题目要求最好不要申请额外空间,这就须要技巧了,看到一个非常巧妙的方法:先将矩阵沿着对角线翻转,再上下翻转。就能够实现顺时针旋转90度的效果。详细看例如以下的样例:

1 2 3        5 4 3       7 8 1
8 9 4    ->  6 9 2   ->  6 9 2
7 6 5        7 8 1       5 4 3

两次翻转相应的坐标须要细心。不然非常easy搞错。

AC源代码

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(matrix)
        for row in range(n):
            for column in range(n - row):
                matrix[row][column], matrix[n - 1 - column][n - 1 - row] = matrix[n - 1 - column][n - 1 - row], 
                                                                           matrix[row][column]
        for row in range(n // 2):
            for column in range(n):
                matrix[row][column], matrix[n - 1 - row][column] = matrix[n - 1 - row][column], matrix[row][column]
        # No need, just to test
        return matrix


if __name__ == "__main__":
    assert Solution().rotate([[1, 2, 3], [8, 9, 4], [7, 6, 5]]) == [[7, 8, 1], [6, 9, 2], [5, 4, 3]]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

原文地址:https://www.cnblogs.com/yxysuanfa/p/7225886.html