Problem :

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


My Solution :

class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
move = len(matrix)-1
for i in range(len(matrix)//2):
for j in range(i, move-i):
temp = matrix[i][j]
matrix[i][j] = matrix[move-j][i]
matrix[move-j][i] = matrix[move-i][move-j]
matrix[move-i][move-j] = matrix[j][move-i]
matrix[j][move-i] = temp


Comment :

나는 이렇게 수동으로 하나씩 회전을 시켰는데, reverse & swap 방식으로 쉽게 풀 수 있다고 한다. Python에서 행과 열을 쉽게 swap 해주는게 바로 zip이다.


Example :

class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
matrix[:] = map(list, zip(*matrix[::-1]))