Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Rotate the matrix by first transposing it (rows become columns),
- then reversing each row to achieve a 90-degree clockwise rotation.
- """
- class Solution:
- def rotate(self, arr: List[List[int]]) -> None:
- n=len(arr)
- for i in range(n):
- for j in range(n):
- if j>i: #it is needed othewise arr[0][1] will swap first with arr[1][0] and again arr[1][0] will swap with arr[0][1] so we have to swap once only.
- arr[i][j],arr[j][i]=arr[j][i],arr[i][j]
- for i in range(n):
- arr[i]=list(reversed(arr[i]))
- #Clean code for the same approach
- class Solution:
- def rotate(self, matrix: List[List[int]]) -> None:
- transposed = list(zip(*matrix)) #*matrix will break matrix into the rows and then zip will take one element from each
- for i in transposed:
- print(i)
- ans=[list(reversed(i)) for i in transposed]
- matrix[:]=ans #to replace a 2d list with 2d list
Advertisement
Add Comment
Please, Sign In to add comment