VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rotate-matrix-180-degree/

⇱ Rotate a Matrix by 180 degree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rotate a Matrix by 180 degree

Last Updated : 28 Jun, 2025

Given a square matrix mat[][], Rotate the matrix by 180 degrees.
Note: Rotating 180Β° clockwise or anticlockwise gives the same result.

Examples:

Input: mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

Output: [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]

Explanation: The output matrix is the input matrix rotated by 180 degrees.

Input: mat[][] = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 0, 1, 2],
[3, 4, 5, 6]]

Output: [[6, 5, 4, 3],
[2, 1, 0, 9],
[8, 7, 6, 5],
[4, 3, 2, 1]]

Explanation: The output matrix is the input matrix rotated by 180 degrees.

[Approach 1] Rotate 90 Degree Twice - O(n^2) Time and O(1) Space

A simple solution is to use the solutions discussed in Rotate 90 Degree Counterclockwise or Rotate 90 Degree Clockwise two times. These solutions require more effort. We can solve this problem more efficiently by directly finding a relationship between the original matrix and 180 degree rotated matrix.

[Approach 2] Using Auxiliary Matrix - O(n^2) Time and O(n^2) Space

If we take a closer look at the examples, we can notice that after rotation, the first element in the top row moves to the last cell in the last row. Similarly, second element in the top row moves to the second last cell in the last row, and so on. In general, we can notice that mat[i][j] needs to be placed at cell [n-i-1][n-j-1]. So, we can create a new matrix and place all the elements at their correct position. Finally, we copy all the elements from new matrix to the original matrix.


Output
9 8 7 
6 5 4 
3 2 1 

[Approach 3] In-Place Swapping - O(n^2) Time and O(1) Space

In the above approach, we are placing mat[i][j] at cell [n-i-1][n-j-1]. However, instead of placing mat[i][j] at cell [n-i-1][n-j-1] in a new matrix, we can observe that mat[n-i-1][n-j-1] is also being placed back at mat[i][j]. So, rather than performing this in two separate matrices, we can handle it in same matrix by simply swapping mat[i][j] and mat[n-i-1][n-j-1].

If the matrix has an odd number of rows, the middle row won’t have an opposite to swap with, so we need to handle it separately. This middle row elements have to be reversed among themselves.

πŸ‘ rotate_a_matrix_by_180_degee
Rotate a matrix 180 degree by in-place swapping

Output
9 8 7 
6 5 4 
3 2 1 
Comment
Article Tags: