48. Rotate Image Leetcode Python

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?

这题是要定义一个Layer 逐层 交换

AB

CD




temp=A

A=C

C=D

D=B

B=temp


代码如下:




    # @param matrix, a list of lists of integers
    # @return a list of lists of integers
    def rotate(self, matrix):
        n=len(matrix)
        num=matrix
        for layer in range(n/2):
            for i in range(layer,n-layer-1):
                tmp=num[layer][i]
                num[layer][i]=num[n-i-1][layer]
                num[n-i-1][layer]=num[n-layer-1][n-i-1]
                num[n-layer-1][n-i-1]=num[i][n-layer-1]
                num[i][n-layer-1]=tmp
        return num


你可能感兴趣的:(LeetCode,array,python)