Created
August 18, 2025 04:25
-
-
Save ssshukla26/7cd2462e9182f361c59036695ecbbb65 to your computer and use it in GitHub Desktop.
Rotate A 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
| # Leetcode 48 : Rotate Image | |
| class Solution: | |
| def rotate90(self, matrix: List[List[int]], offset: Tuple[int, int], n: int): | |
| if n > 1: | |
| # get offset | |
| x, y = offset | |
| # rotate edges : top << left << bottom << right | |
| top_i, top_j = x, y | |
| btm_i, btm_j = x + (n - 1), y + (n - 1) | |
| rgt_i, rgt_j = x, y + (n - 1) | |
| lft_i, lft_j = x + (n - 1), y | |
| # avoid rotating corner twice by processing one less elem | |
| for k in range(n - 1): | |
| top = matrix[top_i][top_j + k] | |
| bottom = matrix[btm_i][btm_j - k] | |
| right = matrix[rgt_i + k][rgt_j] | |
| left = matrix[lft_i - k][lft_j] | |
| matrix[top_i][top_j + k] = left | |
| matrix[lft_i - k][lft_j] = bottom | |
| matrix[btm_i][btm_j - k] = right | |
| matrix[rgt_i + k][rgt_j] = top | |
| # rotate sub-matrix | |
| self.rotate90(matrix, (x + 1, y + 1), n - 2) | |
| return | |
| def rotate(self, matrix: List[List[int]]) -> None: | |
| """ | |
| Do not return anything, modify matrix in-place instead. | |
| """ | |
| if matrix: | |
| self.rotate90(matrix, (0, 0), len(matrix)) | |
| return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment