Rotate Image Leetcode Solution Python

Rotate Image Leetcode

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Solution (Python)

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        # Transpose
        for i in range(0,n):
            for j in range(0,i):
                temp = matrix[i][j]
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = temp
        #print(matrix)
        
        # Reflection (left-right, swap columns)
        for i in range(0,n):
            for j in range(0,n//2):
                temp = matrix[i][j]
                matrix[i][j] = matrix[i][n-j-1]
                matrix[i][n-j-1] = temp

Cracking the Coding Interview: 189 Programming Questions and Solutions

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.