Rotate Image

Problem Id: 48 Difficulty: Medium Tag: Array


Intuition

Let's group all the nodes into several groups where for each group, there are 4 nodes. And each node is in different part of the image (upper-left, upper-right, lower-left, lower-right). And we need to switch these 4 nodes in each group to rotate the image.

Solution


class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        if not matrix:
            return
        n = len(matrix)

        for i in range(n // 2):
            for j in range((n + 1) // 2):
                x1, y1 = i, j
                x2, y2 = j, n - 1 - i
                x3, y3 = n - 1 - i, n - 1 - j
                x4, y4 = n - 1 - j, i
                matrix[x1][y1], matrix[x2][y2], matrix[x3][y3], matrix[x4][y4] = \
                    matrix[x4][y4], matrix[x1][y1], matrix[x2][y2], matrix[x3][y3]