Created
September 10, 2021 13:30
-
-
Save pallabpain/8177af3ec1fb492d69677f3da8eb1e93 to your computer and use it in GitHub Desktop.
Roate a 2D matrix clockwise by 90 degrees
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
""" | |
You are given an n x n 2D matrix that represents an image. | |
Rotate the image by 90 degrees (clockwise) using O(1) extra space | |
""" | |
def rotateImageClockwiseBy90(a): | |
""" | |
The solution here is to find the elements to swap. We will do it | |
in cycles. First, identify the groups: | |
(x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x) | |
Then, depending on the direction, swap them. | |
Here's we'll swap in the clockwise direction | |
""" | |
N = len(a) | |
for x in range(N//2): | |
for y in range(x, N-x-1): | |
t = a[x][y] | |
a[x][y] = a[N-1-y][x] | |
a[N-1-y][x] = a[N-1-x][N-1-y] | |
a[N-1-x][N-1-y] = a[y][N-1-x] | |
a[y][N-1-x] = t | |
return a | |
if __name__ == "__main__": | |
matrix = [[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9]] | |
expected = [[7, 4, 1], | |
[8, 5, 2], | |
[9, 6, 3]] | |
print(rotateImageClockwiseBy90(matrix) == expected) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment