Last active
August 24, 2019 18:49
-
-
Save james4388/671e25604d82e7b45d1ca2eba0abe821 to your computer and use it in GitHub Desktop.
Rotate matrix, inplace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def rotate(mat: List, clockwise: bool=True) -> None: | |
""" Rotate matrix inplace but look like it still use extra memory. run on C """ | |
if clockwise: | |
mat[:] = map(list, zip(*mat[::-1])) | |
else: | |
mat[:] = map(list, list(zip(*mat))[::-1]) | |
return mat | |
def rotate(mat: List, clockwise: bool = True) -> None: | |
""" Traditional way to rotate inplace, no extra memory """ | |
h = len(mat) | |
if not h: | |
return mat | |
w = len(mat[0]) | |
if w < h: # Rectangle | |
# Resize mat to match larger rectangle max(w,h) * max(w,h) | |
n = h | |
col_diff = n - w | |
for row in mat: | |
if len(row) < n: | |
row.extend([None] * col_diff) | |
elif h < w: | |
n = w | |
if clockwise: | |
mat[:] = [[None] * n for i in range(n-h)] + mat | |
else: | |
mat.extend([None] * n for i in range(n-h)) | |
else: | |
n = h | |
n0 = n - 1 # avoid to carry n - i - 1 all the time | |
for i in range(n // 2 + n % 2): | |
for j in range(n // 2): | |
if clockwise: | |
tmp = (mat[n0 - j][i], mat[i][j], mat[j] | |
[n0 - i], mat[n0 - i][n0 - j]) | |
else: | |
tmp = (mat[j][n0 - i], mat[n0 - i] | |
[n0 - j], mat[n0 - j][i], mat[i][j]) | |
(mat[i][j], mat[j][n0 - i], mat[n0 - i] | |
[n0 - j], mat[n0 - j][i]) = tmp | |
# Trim square to rectangle | |
if w < h: # Rectangle | |
if clockwise: | |
mat[:] = mat[:w] | |
else: | |
mat[:] = mat[-w:] | |
elif h < w: | |
for row in mat: | |
row[:] = row[:h] | |
return mat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added rectangle support