Two python solutions with explanation


  • 0
    class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        #solution 1: don't modify in-place
        '''n=len(matrix)
        res=[[matrix[i][j] for i in xrange(n-1,-1,-1)] for j in xrange(n)] #the first row become the first column,and so on.
        '''
        #solution 2: modify in-place: two symmetrically transformations,firstly along diagonal,then along central axis
        n=len(matrix)
        for i in xrange(n):
            for j in xrange(i,n):
                matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
        for i in xrange(n):
            for j in xrange(n/2):
                matrix[i][j],matrix[i][n-1-j]=matrix[i][n-1-j],matrix[i][j]

Log in to reply
 

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