Short in-place solution in Python


  • 0
    B
    class Solution:
        # @param matrix, a list of lists of integers
        # @return a list of lists of integers
        def rotate(self, matrix):
            n = len(matrix)
            if n < 2:
                return matrix
            for offset in range(n/2):
                for i in range(n-1-offset*2):
                    temp = matrix[offset][offset+i]
                    matrix[offset][offset+i] = matrix[-offset-i-1][offset]
                    matrix[-offset-i-1][offset] = matrix[-offset-1][-offset-i-1]
                    matrix[-offset-1][-offset-i-1] = matrix[offset+i][-offset-1]
                    matrix[offset+i][-offset-1] = temp
            return matrix
    

    The idea would be start rotating the most outer edge first.

    Note that if n is odd, there's no need to rotate the innermost one because it's only 1x1.


Log in to reply
 

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