Skip to content

[LC] 48. Rotate Image #120

@seungriyou

Description

@seungriyou

48. Rotate Image

Approach

in-place로 2D matrix를 회전하는 방법은 다음과 같이 원소를 swap 하면 된다.

Clockwise Rotation

def rotate_clockwise(matrix: List[List[int]]) -> None:
    """
    [ clockwise rotation (in-place) ]
        1. matrix reverse
        2. matrix transpose
    """

    n = len(matrix)

    # (1) reverse
    for r in range(n // 2):
        matrix[r], matrix[n - r - 1] = matrix[n - r - 1], matrix[r]

    # (2) transpose
    for r in range(n):
        for c in range(r):
            matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]

Counterclockwise Rotation

def rotate_counterclockwise(matrix: List[List[int]]) -> None:
    """
    [ counterclockwise rotation (in-place) ]
        1. matrix row 별 reverse
        2. matrix transpose
    """

    n = len(matrix)

    # (1) row reverse
    for r in range(n):
        for c in range(n // 2):
            matrix[r][c], matrix[r][n - c - 1] = matrix[r][n - c - 1], matrix[r][c]

    # (2) transpose
    for r in range(n):
        for c in range(r):
            matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]

Complexity

  • Time: O(n^2)
  • Space: O(1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Grind 169Grind 169 문제집에만 속하는 문제LeetCode ✨LeetCode 문제Tip 👍새롭게 알게 된 꿀팁

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions