일하는/Algorithm, Coding

[LeetCode][릿코드][Python][#48] Rotate Image

김논리 2021. 11. 16. 11:32

https://leetcode.com/problems/rotate-image/

 

Rotate Image - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

 

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Example 3:

Input: matrix = [[1]]
Output: [[1]]

Example 4:

Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

 

Constraints:

  • matrix.length == n
  • matrix[i].length == n
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

rotate 전/후 좌표값을 이용하여 예제 1 입력을 생각해 보면 다음과 같다.

주황색을 row, 파란색을 col 값이라고 두면, rotate 후 좌표는 그림 오른쪽과 같은 규칙성을 갖게 된다.

이를 코드로 구현하면 다음과 같다.

from copy import deepcopy

class Solution:
    def rotate(self, matrix):
        tmp, n = deepcopy(matrix), len(matrix)
        for r in range(n):
            for c in range(n):
                matrix[r][c] = tmp[n-1-c][r]

deepcopy를 하는 이유는, 이전 matrix 값을 유지하기 위해서이다.