- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to rotate square matrix by 90 degrees counterclockwise in Python
Suppose we have a square matrix, we have to rotate it 90 degrees counter-clockwise.
1 | 4 | 7 |
2 | 5 | 8 |
3 | 6 | 9 |
then the output will be
7 | 8 | 9 |
4 | 5 | 6 |
1 | 2 | 3 |
To solve this, we will follow these steps −
if matrix is empty, then
return a blank list
n := row count of matrix
for each row in matrix, do
reverse the row
for i in range 0 to n−1, do
for j in range 0 to i−1, do
swap matrix[i, j] and matrix[j, i]
return matrix
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): if not matrix or not matrix[0]: return [] n = len(matrix) for row in matrix: row.reverse() for i in range(n): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] return matrix ob = Solution() matrix = [ [1, 4, 7], [2, 5, 8], [3, 6, 9] ] print(ob.solve(matrix))
Input
[ [1, 4, 7], [2, 5, 8], [3, 6, 9] ]
Output
[ [7, 8, 9], [4, 5, 6], [1, 2, 3]]
- Related Articles
- Write a program in Java to rotate a matrix by 90 degrees in anticlockwise direction
- How can I rotate xtick labels through 90 degrees in Matplotlib?
- Rotate a matrix by 90 degree without using any extra space in C++
- Rotate Matrix in Python
- Java Program to Rotate Matrix Elements
- Rotate a matrix by 90 degree in clockwise direction without using any extra space in C++
- How to rotate a matrix of size n*n to 90 degree using C#?
- Rotate div to -20 degrees angle with CSS
- Python program to cyclically rotate an array by one
- Python program to right rotate a list by n
- Python program to rotate doubly linked list by N nodes
- How to rotate a matrix of size n*n to 90-degree k times using C#?
- Check if matrix can be converted to another matrix by transposing square sub-matrices in Python
- Python Program to Remove First Diagonal Elements from a Square Matrix
- Program to count number of square submatrices in given binary matrix in Python

Advertisements