VOOZH about

URL: https://www.geeksforgeeks.org/dsa/turn-an-image-by-90-degree/

⇱ Rotate a Rectangular Image by 90 Degree Clockwise - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rotate a Rectangular Image by 90 Degree Clockwise

Last Updated : 23 Jul, 2025

Given an image represented by m x n matrix, rotate the image by 90 degrees in clockwise direction. Please note the dimensions of the result matrix are going to n x m for an m x n input matrix.

Input: 1   2   3 4
               5 6 7 8
               9 10 11 12
13 14 15 16
Output:  13   9   5 1
               14 10 6 2
               15 11 7 3
16 12 8 4

Another Example:

👁 matrix_rotatedrawio

[Best Approach] – O(m x n) Time

We mainly need to move first row elements to last column, second row elements to second last column.

Let us first try to find out a pattern to solve the problem for a 4 x 4 matrix.

mat[0][0] goes to mat[0][3]
mat[0][1] goes to mat[1][3]
………………………………………
mat[1][0] goes to mat[0][2]
……………………………………..
mat[3][3] goes to mat[3][0]

Do you see a pattern? Mainly we need to move mat[i][j] to mat[j][n-i-1].


Output
9 5 1 
10 6 2 
11 7 3 
12 8 4 

[Alternate Approach] – O(m x n) Time

When you think about rotating a matrix 90 degrees clockwise, each element moves to a new position. The top row becomes the right column, the second row becomes the second-right column, and so forth. If we first transpose the matrix and then find reverse of every row, we get the desired result.

Follow the given steps to solve the problem:

1  2  3                                 1  4  7                                            7  4  1

4  5  6   —Transpose->   2  5  8     —-Reverse rows—->   8  5  2  

7  8  9                                 3  6  9                                          9  6  3


Output
9 5 1 
10 6 2 
11 7 3 
12 8 4 

Refer to the below article for rotating the square matrix by 90 degrees inplace.

Inplace rotate square matrix by 90 degrees

Comment
Article Tags:
Article Tags: