Skip to content

Instantly share code, notes, and snippets.

@macroxela
Created May 10, 2020 15:03
Show Gist options
  • Save macroxela/60733f269e64c637c1b23524a66861fc to your computer and use it in GitHub Desktop.
Save macroxela/60733f269e64c637c1b23524a66861fc to your computer and use it in GitHub Desktop.
Rotates N x N matrix by 90, 180, or 270 degrees without using any extra space
########################################################################
# Rotates N x N matrix by 90, 180, or 270 degrees without using any
# extra space.
########################################################################
#Swap elements from two sets of indicies in matrix
def swapMat(matrix, i1, j1, i2, j2):
temp = matrix[i1][j1]
matrix[i1][j1] = matrix[i2][j2]
matrix[i2][j2] = temp
#Rotates matrix by 90 degrees
def matrix90rot(matrix):
size = len(matrix)
#Transpose Matrix
for i in range(size):
for j in range(i, size):
swapMat(matrix, i, j, j, i)
#Swap columns for proper positions
for i in range(size):
for j in range(int(size/2)):
swapMat(matrix, i, j, i, size-1-j)
#Rotates matrix by 90, 180, or 270 degrees
def MatrixRotation(matrix, deg):
if deg%360 == 90:
matrix90rot(matrix)
elif deg%360 == 180:
matrix90rot(matrix)
matrix90rot(matrix)
elif deg%360 == 270:
matrix90rot(matrix)
matrix90rot(matrix)
matrix90rot(matrix)
def printMat(m):
for i in m:
print(i)
print(" ")
'''
m = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
n = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
printMat(m)
MatrixRotation(m, 270)
printMat(m)
printMat(n)
MatrixRotation(n, 180)
printMat(n)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment