This Python program takes a 2D matrix and rotates it 90 degrees clockwise.
To achieve this, it first transposes the matrix and then reverses each row.
def rotate_90(matrix: list[list[int]]) -> list[list[int]]:
# Transpose
transposed = list(zip(*matrix))
# Reverse each row
rotated = [list(row)[::-1] for row in transposed]
return rotated
def print_matrix(matrix: list[list[int]]):
for row in matrix:
print(" ".join(str(val) for val in row))
# Sample data
original = [
[12, 11, 10],
[22, 21, 20],
[32, 31, 30],
[42, 41, 40]
]
print("Original matrix:")
print_matrix(original)
rotated = rotate_90(original)
print("\nMatrix after 90-degree rotation:")
print_matrix(rotated)
Original matrix:
12 11 10
22 21 20
32 31 30
42 41 40
Matrix after 90-degree rotation:
42 32 22 12
41 31 21 11
40 30 20 10