Created
December 24, 2014 17:55
-
-
Save alisey/08c44fa9c4ebf59a6334 to your computer and use it in GitHub Desktop.
Rotate matrix in Python
This file contains 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 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