Skip to content

Instantly share code, notes, and snippets.

@scheler
Last active July 22, 2018 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scheler/2f8796ee473af81da8fd7fd9565141fc to your computer and use it in GitHub Desktop.
Save scheler/2f8796ee473af81da8fd7fd9565141fc to your computer and use it in GitHub Desktop.
Rotate right a 2d array by 90 degrees using constant space usage
def rotateSquare(a, start, length):
lastIndex = start + length - 1
for i in range(length-1):
temp = a[start][start + i]
a[start][start + i] = a[lastIndex - i][start]
a[lastIndex - i][start] = a[lastIndex][lastIndex - i]
a[lastIndex][lastIndex - i] = a[start + i][lastIndex]
a[start + i][lastIndex] = temp
# Rotate right a 2D array by 90 degrees
def rotate2DArray(a):
i = 0
squareLength = len(a)
while True:
rotateSquare(a, i, squareLength)
i += 1
squareLength -= 2
if squareLength < 2:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment