⬅ Previous Topic
Set Matrix ZeroesNext Topic ⮕
Print Matrix in Spiral Manner⬅ Previous Topic
Set Matrix ZeroesNext Topic ⮕
Print Matrix in Spiral MannerTopic Contents
Given a square matrix of size n x n
, rotate the entire matrix by 90 degrees in the clockwise direction. The rotation should be done in-place, meaning no extra matrix should be used for the transformation.
n x n
square matrix.matrix[i][j]
with matrix[j][i]
for all i < j
.def rotate_matrix(matrix):
n = len(matrix)
# Transpose the matrix
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
# Reverse each row
for row in matrix:
row.reverse()
return matrix
# Sample Input
mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
rotated = rotate_matrix(mat)
for row in rotated:
print(row)
⬅ Previous Topic
Set Matrix ZeroesNext Topic ⮕
Print Matrix in Spiral MannerYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.