imashutosh51

Rotate Image

Jan 28th, 2026 (edited)
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. """
  2. Rotate the matrix by first transposing it (rows become columns),
  3. then reversing each row to achieve a 90-degree clockwise rotation.
  4. """
  5. class Solution:
  6.     def rotate(self, arr: List[List[int]]) -> None:
  7.         n=len(arr)
  8.         for i in range(n):
  9.             for j in range(n):
  10.                 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.
  11.                     arr[i][j],arr[j][i]=arr[j][i],arr[i][j]
  12.        
  13.         for i in range(n):
  14.             arr[i]=list(reversed(arr[i]))
  15.  
  16. #Clean code for the same approach
  17. class Solution:
  18.     def rotate(self, matrix: List[List[int]]) -> None:
  19.         transposed = list(zip(*matrix)) #*matrix will break matrix into the rows and then zip will take one element from each
  20.         for i in transposed:
  21.             print(i)
  22.         ans=[list(reversed(i)) for i in transposed]
  23.         matrix[:]=ans #to replace a 2d list with 2d list
  24.        
Advertisement
Add Comment
Please, Sign In to add comment