1 line in Python


  • 12
    L
    class Solution(object):
        def rotate(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            """
            matrix[::] = zip(*matrix[::-1])

  • 1

    38 ms, easy to understand, first transpose, then flip horizontally

    class Solution(object):
        def rotate(self, matrix):
            n = len(matrix)
            # transpose
            for i in range(n):
                for j in range(i + 1, n):
                    tmp = matrix[i][j]
                    matrix[i][j] = matrix[j][i]
                    matrix[j][i] = tmp
            # flip horizontally
            for i in range(n):
                for j in range(n/2):
                    tmp = matrix[i][j]
                    matrix[i][j] = matrix[i][n - 1 - j]
                    matrix[i][n - 1- j] = tmp
    

  • 0
    Z

    my solution:

    def rotate(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            """
            length = len(matrix)
            for i in range(int(length/2)):
                count = 0
                for j in range(i,length-1-i):
    
                    matrix[i][j], matrix[i+count][length-i-1], matrix[length-i-1][length-j-1], matrix[length-j-1][i] = \
                    matrix[length-j-1][i], matrix[i][j], matrix[i+count][length-i-1], matrix[length-i-1][length-j-1]
    
                    count += 1
    

  • 0
    W

    @leetcoder07 said in 1 line in Python:

    matrix[::] = zip(*matrix[::-1])

    I wonder if it meets the question. Because it changes list[list,list,...] to list[tuple,tuple,...]


  • 0
    A

    @leetcoder07
    it gives this error:
    Do not return anything, modify matrix in-place instead.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.