Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- Binary
- easy
- matrix
- Depth-first Search
- Array
- string
- list
- 이진트리
- leetcode
- backtracking
- hash table
- binary search
- sorting
- Medium
- binary tree
- two pointers
- dfs
- 리트코드
- recursive
- 문자열
- DP
- tree
- Python
- HashTable
- math
- 재귀
- 쉬움
- 중간
- 미디움
- linked list
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 48(Rotate Image, Python) 본문
1. 문제 링크
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
2. 문제 설명
- 주어진 행렬을 시계방향으로 90도 회전하는 것
- 그런데 제자리 알고리즘(in-place)으로 해결해야한다. 새로운 행렬을 만들어 반환하면 안된다.
- 예시) matrix = [[1,2,3],[4,5,6],[7,8,9]]가 주어지면 [[7,4,1],[8,5,2],[9,6,3]]를 반환
3. 처음 풀이
- 가끔 나의 수학적 지식이 리트코드 문제를 해결할 때 핵심 역할을 하면 되게 뿌듯하다.
- 이 문제 역시 그렇다. 회전을 바로 생각하면 꽤 복잡하다.
- 하지만 평면에서 선대칭 변환을 두 번하면 회전 변환이 된다는 것을 나는 알고 있다.
- 따라서 90도 회전은 주대각(위 그림에서 1, 5, 9)에 대한 대칭을 한 후 세로 선 대칭(위 그림에서 4, 5, 6)하면 90도 회전이 된다.
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
#transpose, 주대각에 대해 대칭
for i in range(len(matrix)):
for j in range(i+1, len(matrix)):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
#세로 선에 대한 대칭
for i in range(len(matrix)):
for j in range(len(matrix)//2):
matrix[i][j], matrix[i][len(matrix)-j-1] = matrix[i][len(matrix)-j-1], matrix[i][j]
4. 다른 풀이
- 논리는 같지만 코드가 훨씬 심플하다.
- zip(*matrix) 하면 [[1,2,3], [4,5,6], [7,8,9]]의 각 리스트의 같은 인덱스끼리 묶어서 [[1,4,7], [2,5,8], [3,6,9]]가 된다. 즉 주대각 대칭이 된다.
- 각각을 x[::-1]하면 역순이 되어 세로선 대칭이 된다.
- 이를 기존 행렬에 덮어 씌운다.
- 마지막에 matrix = [x[::-1] for x in list(zip(*matrix))]을 하면 새로운 matrix 리스트가 생성되어 기존과는 주소가 다른 리스트가 생성된다.
- 하지만 matrix[:]=[x[::-1] for x in list(zip(*matrix))]라고 하면 기존의 리스트에 내용을 변경하는 것이다.
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
matrix[:] = [x[::-1] for x in list(zip(*matrix))]
5. 배운 점
- zip함수를 잘 쓰면 코드가 심플해진다.
- caller가 전달한 리스트를 내용만 바꾸어 그대로 반환해야할 때는 슬라이싱 사용
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 50(Pow(x, n), Python) (1) | 2024.01.07 |
---|---|
LeetCode 49(Groupd Anagrams, Python) (0) | 2024.01.06 |
LeetCode 47(Permutations II, Python) (0) | 2024.01.04 |
LeetCode 46(Permutations, Python) (1) | 2024.01.03 |
LeetCode 45(Jump Game II, Python) (0) | 2024.01.02 |