5 Best Ways to Rotate a Square Matrix by 90 Degrees Counterclockwise in Python

Rate this post

πŸ’‘ Problem Formulation: Rotating a square matrix by 90 degrees counterclockwise is a common task in areas like image processing and puzzle solving. Given an n x n matrix, the goal is to rotate it in place (if possible) or produce a new matrix that represents the original matrix after a 90-degree counterclockwise turn. For instance, if the input matrix is [[1,2,3],[4,5,6],[7,8,9]], the output should be [[3,6,9],[2,5,8],[1,4,7]].

Method 1: Using Nested Loops

This method entails creating a new matrix and then populating it with elements from the original matrix using nested loops. The outer loop goes through each layer of the square matrix, while the inner loop shifts the elements within that layer to their new positions.

Here’s an example:

def rotate_matrix(matrix):
    n = len(matrix)
    new_matrix = [[0]*n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            new_matrix[n-1-j][i] = matrix[i][j]
    return new_matrix

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotated_matrix = rotate_matrix(matrix)
print(rotated_matrix)

Output:

[[3, 6, 9], [2, 5, 8], [1, 4, 7]]

Each element from the original matrix is assigned to its new rotated position in the new matrix. The expression new_matrix[n-1-j][i] computes the destination indices for each element, effectively rotating the matrix.

Method 2: List Comprehension

This method leverages the power of list comprehension to achieve the rotation in a more Pythonic way. It is more concise and potentially easier to read, using list comprehension to reverse the order of columns and then zip to combine rows into columns.

Here’s an example:

def rotate_matrix(matrix):
    return [list(row) for row in zip(*matrix[::-1])]

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotated_matrix = rotate_matrix(matrix)
print(rotated_matrix)

Output:

[[3, 6, 9], [2, 5, 8], [1, 4, 7]]

This approach captures the beauty of Python’s list comprehensions and functional programming utilities like zip to rotate the matrix in a single line within the function.

Method 3: Matrix Transposition and Reversal

With this method, the matrix is first transposed (rows become columns, and vice versa), and then every row of the transposed matrix is reversed. This approach uses built-in operations to achieve the rotation without the direct use of element-level manipulation.

Here’s an example:

def rotate_matrix(matrix):
    matrix[:] = map(list, zip(*matrix))
    for row in matrix:
        row.reverse()
    return matrix

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotated_matrix = rotate_matrix(matrix)
print(rotated_matrix)

Output:

[[3, 6, 9], [2, 5, 8], [1, 4, 7]]

In this method, zip(*matrix) perfunctorily transposes the matrix, while row.reverse() takes care of reversing each row in-place, delivering the desired rotation.

Method 4: In-Place Rotation

For square matrices, it’s possible to perform the rotation in-place to save space. This method involves cyclically moving four rectangles into each other’s places, one value at a time.

Here’s an example:

def rotate_matrix(matrix):
    n = len(matrix)
    for i in range(n//2):
        for j in range(i, n-i-1):
            temp = matrix[i][j]
            matrix[i][j] = matrix[j][n-i-1]
            matrix[j][n-i-1] = matrix[n-i-1][n-j-1]
            matrix[n-i-1][n-j-1] = matrix[n-j-1][i]
            matrix[n-j-1][i] = temp
    return matrix

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate_matrix(matrix)
print(matrix)

Output:

[[3, 6, 9], [2, 5, 8], [1, 4, 7]]

In this in-place algorithm, the rotation is done layer by layer from the outermost to the innermost, swapping elements directly without using extra space for another matrix.

Bonus One-Liner Method 5: Using NumPy

With the NumPy library, matrix operations can be done very efficiently with simple one-liners. This method utilizes NumPy’s `rot90()` function to rotate the matrix.

Here’s an example:

import numpy as np

matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
rotated_matrix = np.rot90(matrix)
print(rotated_matrix)

Output:

[[3 6 9]
 [2 5 8]
 [1 4 7]]

NumPy’s rot90() function provides a concise and efficient way to rotate matrices. It’s well-optimized and hence suitable for large matrices or performance-critical applications.

Summary/Discussion

  • Method 1: Nested Loops. Scalable. Possible overhead for large matrices.
  • Method 2: List Comprehension. Pythonic and straight-forward. Can be less intuitive for those unfamiliar with zip.
  • Method 3: Transposition and Reversal. Uses native functions effectively. Might lack readability for beginners.
  • Method 4: In-Place Rotation. Space-efficient. Complexity makes it harder to understand.
  • Method 5: NumPy Library. Extremely efficient and concise. Requires NumPy installation.