Rotating a matrix by 90 degrees is a common problem in computer science, particularly in image processing and computer graphics. This post explores efficient ways to achieve this in Python, offering explanations and code examples to help you master this task.
Understanding the Problem
A matrix is a two-dimensional array of numbers. Rotating a matrix by 90 degrees clockwise means shifting each element to a new position, effectively turning the matrix on its side. For example:
Original Matrix:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Rotated Matrix (90 degrees clockwise):
[
[7, 4, 1],
[8, 5, 2],
[9, 6, 3]
]
Method 1: Using Zip and List Comprehension
This elegant approach uses Python’s built-in zip
function and list comprehension for a concise and efficient solution.
def rotate_matrix_zip(matrix):
"""Rotates a square matrix by 90 degrees clockwise using zip and list comprehension."""
return [list(row) for row in zip(*matrix[::-1])]
= [
matrix 1, 2, 3],
[4, 5, 6],
[7, 8, 9]
[
]
= rotate_matrix_zip(matrix)
rotated_matrix print(rotated_matrix) # Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
matrix[::-1]
reverses the matrix, and zip(*matrix)
transposes it. Combining these operations achieves the 90-degree rotation.
Method 2: In-place Rotation (More Efficient for Large Matrices)
For larger matrices, an in-place rotation is more memory-efficient. This method modifies the original matrix directly, avoiding the creation of a new matrix.
def rotate_matrix_inplace(matrix):
"""Rotates a square matrix by 90 degrees clockwise in-place."""
= len(matrix)
n for i in range(n // 2):
for j in range(i, n - i - 1):
= matrix[i][j]
temp = matrix[j][n - 1 - i]
matrix[i][j] - 1 - i] = matrix[n - 1 - i][n - 1 - j]
matrix[j][n - 1 - i][n - 1 - j] = matrix[n - 1 - j][i]
matrix[n - 1 - j][i] = temp
matrix[n
= [
matrix 1, 2, 3],
[4, 5, 6],
[7, 8, 9]
[
]
rotate_matrix_inplace(matrix)print(matrix) # Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
This method uses a temporary variable (temp
) to swap elements efficiently, layer by layer.
Handling Non-Square Matrices
The above methods assume a square matrix (same number of rows and columns). Rotating a rectangular matrix by 90 degrees requires a more complex approach, often involving padding or resizing to maintain a rectangular shape. We’ll look at this in a future post.
Choosing the Right Method
For smaller matrices, the zip
and list comprehension method is concise and easy to understand. However, for larger matrices where memory efficiency is crucial, the in-place rotation method is recommended. The choice depends on the specific application and the size of the matrices being processed.