코테 문제 풀이
[리트코드] 48. Rotate Image
미니모아
2022. 4. 14. 22:00
반응형
48. Rotate Image
문제
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.
제한사항
- n == matrix.length == matrix[i].length
- 1 <= n <= 20
- -1000 <= matrix[i][j] <= 1000
풀이
그림을 그려서 규칙을 확인해보면
[0] [0] 부터 [n//2 - 1] [(n + 1) // 2 -1]을 시작점으로 해서
b = a
a = d
d = c
c = b
로 값이 변경되는 것을 확인할 수 있다.
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n//2):
for j in range((n + 1)//2):
tmp = matrix[j][n-i-1] # b
matrix[j][n-i-1] = matrix[i][j] # b = a
matrix[i][j] = matrix[n - j - 1][i] # a = d
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]# d =c
matrix[n - i - 1][n - j - 1] = tmp # c = b
제한 조건 때문에 그렇지 사실 한 줄로도 만들 수 있다.
[list(reversed(i)) for i in zip(*matrix)] # 시계 방향 90도 회전
[i for i in zip(*matrix)][::-1] # 반시계 방향 90도 회전
반응형