Efficient image rotation by clockwise 90 degrees


  • 0
    A
    class Solution:
        def rotate(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            """
            # length of matrix as integer
            size = int(len(matrix))
    
            # Running j, which is along height, from 0 to size-1
            for j in range(int(size/2)):
                # If you think carefully, you only need to use i in range from j to size-1-j. This should rotate the entire matrix and avoid rotating elements you have already rotated.
                for i in range(j, size-1-j):
                    # Swapping the four points as calculated w.r.t. (j, i)
                    temp = matrix[size-1-i][j]
                    matrix[size-1-i][j] = matrix[size-1-j][size-1-i]
                    matrix[size-1-j][size-1-i] = matrix[i][size-1-j]
                    matrix[i][size-1-j] = matrix[j][i]
                    matrix[j][i] = temp
    

Log in to reply
 

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