Advertisement
hoangreal

Rotate Matrix 90 degree

Oct 21st, 2024
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | Source Code | 0 0
  1. """
  2. You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
  3.  
  4. You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
  5. """
  6.  
  7. class Solution:
  8.     def rotate(self, matrix: List[List[int]]) -> None:
  9.         """
  10.        Do not return anything, modify matrix in-place instead.
  11.  
  12.        mat[r][c] -> mat[c][(n - 1) - r]
  13.  
  14.        => mat[r][c] <- mat[c][r] <- mat[c][(n-1)-r]
  15.        """
  16.         n = len(matrix)
  17.        
  18.         for r in range(len(matrix)):
  19.             for c in range(len(matrix[0])):
  20.                 if r < c:
  21.                     continue
  22.                 matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
  23.        
  24.         for c in range(len(matrix)):
  25.             for r in range(len(matrix)):
  26.                 if (n - 1) - r > r:
  27.                     continue
  28.                 matrix[c][r], matrix[c][(n - 1) - r] = matrix[c][(n - 1) - r], matrix[c][r]
  29.  
  30.         return
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement