Rotate a matrix in Python

Rotate a matrix in Python:-

firstly rotating a matrix in Python involves in transforming the rows into columns. Inorder to rotate a matrix in python we have to do two tasks that is

1) Transpose the matrix

2) Reversing the rows

firstly we have to do that in a transposition each element at position (i,j)(i, j) in the original matrix is moved to position (j,i)(j, i) in the new matrix. This means that rows become columns.

We initialize an empty list transposed_matrix to hold the transposed version of the original matrix.

We loop through each column index i of the original matrix.

For each column index i, we create a new row by collecting the elements from each row j at column i.

This new row is appended to transposed_matrix.

Then we have to reverse Each Row of the Transposed Matrix then After transposing, each row is reversed to complete the 90-degree rotation. After the matrix is transposed, we iterate through each row in transposed_matrix and reverse it in place using the reverse() method. the original matrix is effectively rotated 90 degrees clockwise. This method can be generalized and applied to any n×nn \times n matrix.

first step is:-Transpose the matrix

def rotate_matrix(matrix):
transposed_matrix = []
for i in range(len(matrix[0])):
transposed_row = []
for j in range(len(matrix)):
transposed_row.append(matrix[j][i])
transposed_matrix.append(transposed_row)

Second step is:-Reverse each row in the transposed matrix
for row in transposed_matrix:
row.reverse()
return transposed_matrix

rotated_matrix = rotate_matrix(matrix)
for row in rotated_matrix:
print(row)

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top