
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Rotate Matrix in Python
Suppose we have one n x n 2D matrix. We have to rotate this matrix 90 degrees clockwise. So if the matrix is like-
1 | 5 | 7 |
9 | 6 | 3 |
2 | 1 | 3 |
Then the output will be
2 | 9 | 1 |
1 | 6 | 5 |
3 | 3 | 7 |
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]
- for j in range 0 to length of matrix
Let us see the following implementation to get better understanding −
Example Code (Python)
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]]
- Related Articles
- Program to rotate square matrix by 90 degrees counterclockwise in Python
- Rotate the matrix 180 degree in Java?
- Java Program to Rotate Matrix Elements
- Golang Program To Rotate Matrix Elements
- Rotate Array in Python
- Rotate String in Python
- Rotate Image in Python
- Rotate div with Matrix transforms using CSS
- JavaScript Program for Rotate a Matrix by 180 degrees
- JavaScript Program for Rotate the matrix right by K times
- Rotate a matrix by 90 degree without using any extra space in C++
- String slicing in Python to rotate a string
- How to rotate an image in OpenCV Python?
- Python - Ways to rotate a list
- Write a program in Java to rotate a matrix by 90 degrees in anticlockwise direction

Advertisements