48. Rotate Image (Python)
Source
https://leetcode.com/problems/rotate-image/
Rotate Image - LeetCode
Can you solve this real interview question? 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 [https://en.wikipedia.org/wiki/In-place_algorithm], which m
leetcode.com
Code
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):
for j in range(i, n - 1 - i):
self.temp(i, j, matrix)
def temp(self, i, j, matrix):
n = len(matrix)
first = matrix[i][j]
matrix[i][j] = matrix[n - 1 - j][i]
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]
matrix[j][n - 1 - i] = first
How to solve?
90도 회전하면
matrix[ i ][ j ]
-> matrix[ n - 1 - j ][ i ]
-> matrix[ n - 1 - i ][ n - 1 - j ]
-> matrix[ j ][ n - 1 - i ]
-> matrix[ i ][ j ]
위와 같은 순서로 회전한다.
재귀 등을 이용해 풀 수 있을 것 같은데 방법이 잘생각나지 않아 하드코딩으로 했다.
Reviewing the best code
Easy Python from scratch (2 Steps) - Rotate Image - LeetCode
View bw1226's solution of Rotate Image on LeetCode, the world's largest programming community.
leetcode.com
# reverse
l = 0
r = len(matrix) -1
while l < r:
matrix[l], matrix[r] = matrix[r], matrix[l]
l += 1
r -= 1
# transpose
for i in range(len(matrix)):
for j in range(i):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
1. reverse에서 row의 자리가 반대로 변하고
2. transpose에서 대각선을 기준으로 row와 column이 서로 교환된다.
'Problem solve' 카테고리의 다른 글
[Leetcode] 27. Remove Element (JavaScript) (0) | 2023.06.09 |
---|---|
[Leetcode] 26. Remove Duplicates from Sorted Array (0) | 2023.05.16 |
[Leetcode] 11. Container With Most Water (JavaScript) (0) | 2023.05.07 |
[Leetcode] 28. Find the Index of the First Occurrence in a String (JavaScript) (0) | 2023.05.06 |
[LeetCode] 35. Search Insert Position (Javascript) (0) | 2023.04.24 |