Skip to content

Instantly share code, notes, and snippets.

@alisey
Created December 24, 2014 17:55
Show Gist options
  • Save alisey/08c44fa9c4ebf59a6334 to your computer and use it in GitHub Desktop.
Save alisey/08c44fa9c4ebf59a6334 to your computer and use it in GitHub Desktop.
Rotate matrix in Python
def swap(matrix, r1, c1, r2, c2):
matrix[r1][c1], matrix[r2][c2] = matrix[r2][c2], matrix[r1][c1]
def transpose(matrix):
for row in range(len(matrix)):
for col in range(row):
swap(matrix, row, col, col, row)
def flip_vertical(matrix):
size = len(matrix)
for row in range(size // 2):
for col in range(size):
swap(matrix, row, col, size - row - 1, col)
def rotate(matrix):
transpose(matrix)
flip_vertical(matrix)
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
rotate(A)
print(A)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment