Skip to content

Instantly share code, notes, and snippets.

@james4388
Last active August 24, 2019 18:49
Show Gist options
  • Save james4388/671e25604d82e7b45d1ca2eba0abe821 to your computer and use it in GitHub Desktop.
Save james4388/671e25604d82e7b45d1ca2eba0abe821 to your computer and use it in GitHub Desktop.
Rotate matrix, inplace
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
@james4388
Copy link
Author

james4388 commented Aug 24, 2019

Added rectangle support

a = [[1, 2, 3, 4, 5, 6, 7]]
rotate(a)
[
  [1],
  [2],
  [3],
  [4],
  [5],
  [6],
  [7]
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment