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

For example,

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

Practice this problem

If we swap elements of the first row with the last row elements in reverse order, elements of the second row with the elements of the second last row in reverse order, and so on… we will get our desired matrix. Note that if the matrix has odd dimensions, reverse elements of the middle row.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

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

Java


Download  Run Code

Output:

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

Python


Download  Run Code

Output:

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

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

 
Related Posts:

In-place rotate matrix by 90 degrees in a clockwise direction