Last active
September 21, 2021 10:55
-
-
Save codecakes/2f05eae36dfe56f6310744c76307f742 to your computer and use it in GitHub Desktop.
clockwise rotate 2d matrix
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
class Solution: | |
def rotate(self, matrix): | |
''' | |
:type matrix: list of list of int | |
:rtype: list of list of int | |
''' | |
# assuming nxm | |
ROWS = len(matrix) | |
COLS = len(matrix[0]) | |
row = ROWS - 1 | |
# initialize empty matrix | |
new_matrix = [[0 for _ in range(COLS)] for _ in range(ROWS)] | |
# do operation | |
for new_col in range(COLS): | |
for new_row in range(ROWS): | |
# col is new_r since row = col index sqr matrix | |
new_matrix[new_row][new_col] = matrix[row][new_row] | |
row -= 1 | |
return new_matrix | |
class Solution: | |
def rotate(self, matrix): | |
''' | |
:type matrix: list of list of int | |
:rtype: list of list of int | |
''' | |
# size = len(matrix) - 1 | |
# layers = len(matrix)//2 | |
# Optimized: still same complexity but with in-place swaps. | |
size = len(matrix) - 1 | |
layers = len(matrix) // 2 | |
for layer in range(0, layers): | |
right_layer_limit = size - layer | |
for row in range(layer, right_layer_limit): | |
top = matrix[layer][row] | |
right = matrix[row][right_layer_limit] | |
bottom = matrix[right_layer_limit][size-row] | |
left = matrix[size-row][layer] | |
matrix[layer][row] = left | |
matrix[row][right_layer_limit] = top | |
matrix[right_layer_limit][size - row] = right | |
matrix[size - row][layer] = bottom | |
return matrix | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment