AlgoMaster Logo

Rotate Image

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force with Extra Space

Intuition:

To rotate a matrix clockwise by 90 degrees, we can utilize an auxiliary matrix. The idea is to iterate through each element of the matrix and place it appropriately in the new matrix. Specifically, each element at position (i, j) in the original matrix will be placed at position (j, n-1-i) in the rotated matrix.

Steps:

  1. Create an auxiliary matrix of the same size as the input matrix.
  2. For each element in the original matrix, calculate its new position in the auxiliary matrix using the formula: rotated[j][n-1-i] = original[i][j].
  3. Copy the rotated matrix back to the original matrix.

Code:

2. In-Place Transpose and Reverse

Intuition:

A more efficient solution is to perform the transformation in place by first transposing the matrix (flipping it over its diagonal) and then reversing each row. Transposing by itself will reorder the elements diagonally, while reversing will yield the required 90-degree clockwise rotation.

Steps:

  1. Transpose the Matrix: Swap each element (i, j) with the element (j, i).
  2. Reverse Each Row: For each row in the transposed matrix, reverse the elements of the row.

Code: