Last active
July 22, 2018 00:36
-
-
Save scheler/2f8796ee473af81da8fd7fd9565141fc to your computer and use it in GitHub Desktop.
Rotate right a 2d array by 90 degrees using constant space usage
This file contains hidden or 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 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