Rotate Matrix in Python

PythonServer Side ProgrammingProgramming

Suppose we have one n x n 2D matrix. We have to rotate this matrix 90 degrees clockwise. So if the matrix is like-

157
963
213

Then the output will be

291
165
337

To solve this, we will follow these steps −

  • Consider temp_mat = [], col := length of matrix – 1
  • for col in range 0 to length of matrix
    • temp := []
    • for row in range length of matrix – 1 down to -1
      • add matrix[row, col] in temp
    • add temp into temp_mat
  • for i in range 0 to length of matrix
    • for j in range 0 to length of matrix
      • matrix[i, j] := temp_mat[i, j]

Let us see the following implementation to get better understanding −

Example Code (Python)

Live Demo

class Solution(object):
   def rotate(self, matrix):
      temp_matrix = []
      column = len(matrix)-1
      for column in range(len(matrix)):
         temp = []
         for row in range(len(matrix)-1,-1,-1):
            temp.append(matrix[row][column])
         temp_matrix.append(temp)
      for i in range(len(matrix)):
         for j in range(len(matrix)):
            matrix[i][j] = temp_matrix[i][j]
      return matrix

ob1 = Solution()
print(ob1.rotate([[1,5,7],[9,6,3],[2,1,3]]))

Input

[[1,5,7],[9,6,3],[2,1,3]]

Output

[[2, 9, 1], [1, 6, 5], [3, 3, 7]]
raja
Published on 05-Jan-2021 07:04:02
Advertisements