def rotate90_clockwise(matrix):
"""Rotates a matrix 90 degrees clockwise."""
rows, cols = len(matrix), len(matrix[0])
rotated = [[0] * rows for _ in range(cols)]
for i in range(rows):
for j in range(cols):
rotated[j][rows - 1 - i] = matrix[i][j] # Mapping to rotated position
return rotated
def print_matrix(matrix):
"""Prints the matrix in a readable format."""
for row in matrix:
print(" ".join(map(str, row)))
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
print("Original Matrix:")
print_matrix(matrix)
rotated = rotate90_clockwise(matrix)
print("\nRotated Matrix:")
print_matrix(rotated)
'''
run:
Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Rotated Matrix:
9 5 1
10 6 2
11 7 3
12 8 4
'''