# Program to rotate square matrix by 90 degrees counterclockwise in Python

PythonServer Side ProgrammingProgramming

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

Live Demo

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]]
Published on 21-Oct-2020 10:30:29