PIXELBANKv9.1.0
Menu

Implement an image rotation algorithm to rotate an n×nn \times n 2D matrix representing an image by 90 degrees in the clockwise direction. The image must be rotated in-place, meaning the input 2D matrix is modified directly without allocating additional memory.

The concept of image rotation is fundamental in image manipulation and computer vision, as it allows for the transformation of images to achieve desired orientations. This process involves applying a transformation matrix to the original image, which can be represented mathematically using linear algebra and matrix operations.

To achieve the rotation, the following steps are involved:

  1. Identify the layers of the matrix, where each layer represents a square ring of elements.
  2. Iterate through each layer, swapping elements in a circular manner to achieve the rotation effect.
(abcd)→(cadb)\begin{pmatrix} a & b \\ c & d \end{pmatrix} \rightarrow \begin{pmatrix} c & a \\ d & b \end{pmatrix}

This technique is widely used in image processing applications.

Example:

Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output:
[[7,4,1],[8,5,2],[9,6,3]]
Reasoning:
  • Start with the original matrix (rows): [1,2,3],[4,5,6],[7,8,9][1,2,3],[4,5,6],[7,8,9].
  • Transpose the matrix (swap rows with columns): [1,4,7],[2,5,8],[3,6,9][1,4,7],[2,5,8],[3,6,9].[1][2]
  • Reverse each row to get a 90° clockwise rotation:
    • 1,4,71,4,7 → 7,4,17,4,1
    • 2,5,82,5,8 → 8,5,28,5,2
    • 3,6,93,6,9 → 9,6,39,6,3.[1][2]
  • The final rotated matrix is [7,4,1],[8,5,2],[9,6,3][7,4,1],[8,5,2],[9,6,3].

Constraints:

1 <= n, m <= 100; Elements of matrix and vector can be integers or floats.

solution.py

Test Results

0/0
Run code to see test results.
Image Rotation - Easy | PixelBank