Given a square matrix, rotate the matrix by 90 degrees in a clockwise direction. The transformation should be done in-place and in quadratic time.

For example,

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

Practice this problem

The idea is to in-place convert the matrix into its transpose first. If we swap the first column with the last column, the second column with the second last column, and so on… we will get our desired matrix.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

[13, 9, 5, 1]
[14, 10, 6, 2]
[15, 11, 7, 3]
[16, 12, 8, 4]

Python


Download  Run Code

Output:

[13, 9, 5, 1]
[14, 10, 6, 2]
[15, 11, 7, 3]
[16, 12, 8, 4]

If we were asked to rotate the matrix in an anti-clockwise manner, we could easily do that, too, using the same logic. The only difference is that instead of swapping columns, we swap rows.

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

[4, 8, 12, 16]
[3, 7, 11, 15]
[2, 6, 10, 14]
[1, 5, 9, 13]

Python


Download  Run Code

Output:

[4, 8, 12, 16]
[3, 7, 11, 15]
[2, 6, 10, 14]
[1, 5, 9, 13]

The time complexity of the proposed solution is O(N2) for an N × N matrix and doesn’t require any extra space.

 
Exercise: In-place rotate the matrix by 180 degrees