Rotating a matrix by 90 degrees is a common problem in programming, especially in the context of 2D arrays. This transformation is often required in fields like computer graphics, game development, and algorithms. In this article, we will explore how to rotate a matrix by 90 degrees in clockwise and counterclockwise directions with step-by-step logic, code examples, and practical applications.


What Does Rotating a Matrix Mean?

Given an N x N matrix, rotating it 90 degrees clockwise rearranges the matrix so that:

  • The first row becomes the last column.
  • The second row becomes the second-last column.
  • The third row becomes the third-last column, and so on.
DALL·E 2024 10 25 10.15.45 A visual representation of three ways to rotate a matrix by 90 degrees showing examples for beginner intermediate and advanced levels. The image fe

Fig – 3 Ways to Rotate a Matrix by 90 Degrees: Beginner to Advanced

Example:

Input Matrix (3x3):
1  2  3  
4  5  6  
7  8  9  

After 90-degree Clockwise Rotation:
7  4  1  
8  5  2  
9  6  3  

The same matrix, when rotated counterclockwise by 90 degrees, would look like:

After 90-degree Counterclockwise Rotation:
3  6  9  
2  5  8  
1  4  7  

Applications of Matrix Rotation

  • Image processing: Rotating or transforming images requires matrix rotation techniques.
  • Computer graphics: Used to rotate elements on the screen or objects in 3D space.
  • Games and puzzles: Rotation logic is common in games like Tetris and in solving Sudoku puzzles.
  • Data science: Matrix manipulation is essential for visualizations and in deep learning frameworks.
DALL·E 2024 10 25 10.18.41 An illustration showing three ways to rotate a matrix by 90 degrees. It features examples of 3x3 and 4x4 matrices with arrows indicating rotation step

Fig-3 Ways to Rotate a Matrix by 90 Degrees: Beginner to Advanced


Approach 1: Transpose and Reverse Rows (Clockwise Rotation)

The most efficient way to rotate a matrix by 90 degrees clockwise is by:

  1. Transposing the matrix: Convert rows into columns.
  2. Reversing each row after the transpose.

Algorithm:

  1. Transpose the matrix by swapping matrix[i][j] with matrix[j][i].
  2. Reverse each row of the transposed matrix.

Python Code:

def rotate_matrix_clockwise(matrix):
    n = len(matrix)

    # Step 1: Transpose the matrix
    for i in range(n):
        for j in range(i, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

    # Step 2: Reverse each row
    for i in range(n):
        matrix[i].reverse()

    return matrix

# Example Usage
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

rotated_matrix = rotate_matrix_clockwise(matrix)
for row in rotated_matrix:
    print(row)

Output:

[7, 4, 1]
[8, 5, 2]
[9, 6, 3]
DALL·E 2024 10 25 10.22.35 A clean and modern visual illustration showcasing three different ways to rotate a matrix by 90 degrees. The design includes distinct examples for 3x3 1

Fig – 3 Ways to Rotate a Matrix by 90 Degrees: Beginner to Advanced


Approach 2: Rotate Counterclockwise by 90 Degrees

For a counterclockwise rotation, we can:

  1. Transpose the matrix.
  2. Reverse each column after the transpose.

Python Code:

def rotate_matrix_counterclockwise(matrix):
    n = len(matrix)

    # Step 1: Transpose the matrix
    for i in range(n):
        for j in range(i, n):
            matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

    # Step 2: Reverse each column
    for j in range(n):
        for i in range(n // 2):
            matrix[i][j], matrix[n - 1 - i][j] = matrix[n - 1 - i][j], matrix[i][j]

    return matrix

# Example Usage
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

rotated_matrix = rotate_matrix_counterclockwise(matrix)
for row in rotated_matrix:
    print(row)

Output:

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

Time and Space Complexity

  • Time Complexity: O(N²), where N is the size of the matrix. This is because each element is accessed once during the transpose and again while reversing.
  • Space Complexity: O(1), since the rotation is performed in-place without using extra memory.

Handling Non-Square Matrices

The above algorithms work for square matrices (N x N). For non-square matrices (M x N):

  1. Create a new matrix of size N x M.
  2. Populate the new matrix with elements from the original matrix in the correct order.

Example:

Input Matrix (2x3):
1 2 3  
4 5 6  

After 90-degree Clockwise Rotation (3x2):
4 1  
5 2  
6 3  

Here’s a Python function for non-square matrices:

def rotate_non_square(matrix):
    rows = len(matrix)
    cols = len(matrix[0])

    # Create a new matrix with transposed dimensions
    rotated_matrix = [[0] * rows for _ in range(cols)]

    for i in range(rows):
        for j in range(cols):
            rotated_matrix[j][rows - 1 - i] = matrix[i][j]

    return rotated_matrix

# Example Usage
matrix = [
    [1, 2, 3],
    [4, 5, 6]
]

rotated_matrix = rotate_non_square(matrix)
for row in rotated_matrix:
    print(row)

Output:

[4, 1]
[5, 2]
[6, 3]

Real-World Examples of Matrix Rotation

  1. Tetris Game: Rotating blocks to fit them into the puzzle.
  2. Image Rotation: Rotating pictures by 90, 180, or 270 degrees in image editing software.
  3. Graphical User Interfaces (GUIs): Rotating icons or elements on a screen.
  4. Robotics and AI: Matrix transformations are used in controlling robotic movements.

Common Mistakes to Avoid

  • Forgetting to transpose correctly: Transposing swaps elements diagonally across the matrix.
  • Mixing up row and column reversal: Clockwise and counterclockwise rotations require different reversal methods.
  • Handling non-square matrices incorrectly: Make sure to adjust dimensions when rotating non-square matrices.

Conclusion

Rotating a matrix by 90 degrees is a fundamental operation in computer science, with applications in graphics, game development, and image processing. By understanding how to transpose and reverse elements, you can rotate both square and non-square matrices efficiently. Mastering these concepts helps you develop a deeper understanding of matrix manipulation techniques used in various real-world scenarios.


Let me know if you need further customization or additional examples!

Read More …

Developing Decentralized Apps (dApps) and Blockchain Solutions – https://kamleshsingad.com/wp-admin/post.php?post=5240&action=edit

Creating Standalone Executables Using PyInstaller: A Complete Guide – https://kamleshsingad.com/wp-admin/post.php?post=5245&action=edit

Interactive Data Visualization with Dash and Plotly – https://kamleshsingad.com/wp-admin/post.php?post=5250&action=edit

Python in IoT and Embedded Systems: Unlocking the Future of Smart Devices – https://kamleshsingad.com/wp-admin/post.php?post=5235&action=edit

Natural Language Processing (NLP) with Transformers: Transforming the Future of AI – https://kamleshsingad.com/wp-admin/post.php?post=5230&action=edit

Automation Using Python: From Scripts to DevOps – https://kamleshsingad.com/wp-admin/post.php?post=5225&action=edit

Here are some outbound links to useful resources on rotating matrices by 90 degrees, with various methods and practical coding examples:

  1. GeeksforGeeks: Rotate a Matrix 90 Degrees
  2. Dev.to: Rotating a 2D Matrix Explained
  3. EnjoyAlgorithms: How to Rotate a Matrix Efficiently

LEAVE A REPLY

Please enter your comment!
Please enter your name here