[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.
C++
#include<iostream>#include<vector>usingnamespacestd;voidrotateMatrix(vector<vector<int>>&mat){intn=mat.size();// Create an auxiliary matrixvector<vector<int>>res(n,vector<int>(n));// move mat[i][j] to mat[n-i-1][n-j-1]for(inti=0;i<n;i++){for(intj=0;j<n;j++){res[i][j]=mat[n-i-1][n-j-1];}}mat=res;}intmain(){vector<vector<int>>mat={{1,2,3},{4,5,6},{7,8,9}};rotateMatrix(mat);for(inti=0;i<mat.size();i++){for(intj=0;j<mat[i].size();j++){cout<<mat[i][j]<<" ";}cout<<"\n";}return0;}
C
#include<stdio.h>voidrotateMatrix(intn,intmat[n][n]){// Create an auxiliary matrixintres[n][n];// move mat[i][j] to mat[n-i-1][n-j-1]for(inti=0;i<n;i++){for(intj=0;j<n;j++){res[i][j]=mat[n-i-1][n-j-1];}}// Copy back to original matrixfor(inti=0;i<n;i++){for(intj=0;j<n;j++){mat[i][j]=res[i][j];}}}intmain(){intn=3;intmat[3][3]={{1,2,3},{4,5,6},{7,8,9}};rotateMatrix(n,mat);for(inti=0;i<n;i++){for(intj=0;j<n;j++){printf("%d ",mat[i][j]);}printf("\n");}return0;}
Java
classGFG{staticvoidrotateMatrix(int[][]mat){intn=mat.length;// Create an auxiliary matrixint[][]res=newint[n][n];// Move mat[i][j] to mat[n-i-1][n-j-1]for(inti=0;i<n;i++){for(intj=0;j<n;j++){res[i][j]=mat[n-i-1][n-j-1];}}// Copy result back to the original matrixfor(inti=0;i<n;i++){System.arraycopy(res[i],0,mat[i],0,n);}}publicstaticvoidmain(String[]args){int[][]mat={{1,2,3},{4,5,6},{7,8,9}};rotateMatrix(mat);for(int[]row:mat){for(intx:row){System.out.print(x+" ");}System.out.println();}}}
Python
defrotateMatrix(mat):n=len(mat)# Create an auxiliary matrixres=[[0]*nfor_inrange(n)]# Move mat[i][j] to mat[n-i-1][n-j-1]foriinrange(n):forjinrange(n):res[i][j]=mat[n-i-1][n-j-1]# Copy result back to original matrixforiinrange(n):forjinrange(n):mat[i][j]=res[i][j]if__name__=="__main__":mat=[[1,2,3],[4,5,6],[7,8,9]]rotateMatrix(mat)forrowinmat:print(" ".join(map(str,row)))
C#
usingSystem;classGFG{staticvoidrotateMatrix(int[,]mat){intn=mat.GetLength(0);// Create an auxiliary matrixint[,]res=newint[n,n];// Move mat[i][j] to mat[n-i-1][n-j-1]for(inti=0;i<n;i++){for(intj=0;j<n;j++){res[i,j]=mat[n-i-1,n-j-1];}}// Copy result back to original matrixfor(inti=0;i<n;i++){for(intj=0;j<n;j++){mat[i,j]=res[i,j];}}}publicstaticvoidMain(){int[,]mat={{1,2,3},{4,5,6},{7,8,9}};rotateMatrix(mat);intn=mat.GetLength(0);intm=mat.GetLength(1);for(inti=0;i<n;i++){for(intj=0;j<m;j++){Console.Write(mat[i,j]+" ");}Console.WriteLine();}}}
JavaScript
functionrotateMatrix(mat){constn=mat.length;// Create an auxiliary matrixconstres=Array.from({length:n},()=>Array(n).fill(0));// Move mat[i][j] to mat[n-i-1][n-j-1]for(leti=0;i<n;i++){for(letj=0;j<n;j++){res[i][j]=mat[n-i-1][n-j-1];}}// Copy result back to original matrixfor(leti=0;i<n;i++){mat[i]=res[i].slice();}}// Driver codeconstmat=[[1,2,3],[4,5,6],[7,8,9]];rotateMatrix(mat);mat.forEach(row=>console.log(row.join(" ")));
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 180 degree by in-place swappingC++
#include<iostream>#include<vector>usingnamespacestd;voidrotateMatrix(vector<vector<int>>&mat){intn=mat.size();// Swap elements from the start and end to// rotate by 180 degreesfor(inti=0;i<n/2;i++){for(intj=0;j<n;j++){swap(mat[i][j],mat[n-i-1][n-j-1]);}}// Handle the middle row if the matrix // has odd dimensionsif(n%2!=0){intmid=n/2;for(intj=0;j<n/2;j++)swap(mat[mid][j],mat[mid][n-j-1]);}}intmain(){vector<vector<int>>mat={{1,2,3},{4,5,6},{7,8,9}};rotateMatrix(mat);for(inti=0;i<mat.size();i++){for(intj=0;j<mat[i].size();j++){cout<<mat[i][j]<<" ";}cout<<"\n";}return0;}
C
#include<stdio.h>voidrotateMatrix(intn,intmat[n][n]){// Swap elements from the start and end to// rotate by 180 degreesfor(inti=0;i<n/2;i++){for(intj=0;j<n;j++){inttemp=mat[i][j];mat[i][j]=mat[n-i-1][n-j-1];mat[n-i-1][n-j-1]=temp;}}// Handle the middle row if the matrix // has odd dimensionsif(n%2!=0){intmid=n/2;for(intj=0;j<n/2;j++){inttemp=mat[mid][j];mat[mid][j]=mat[mid][n-j-1];mat[mid][n-j-1]=temp;}}}intmain(){intn=3;intmat[3][3]={{1,2,3},{4,5,6},{7,8,9}};rotateMatrix(n,mat);for(inti=0;i<n;i++){for(intj=0;j<n;j++){printf("%d ",mat[i][j]);}printf("\n");}return0;}
Java
classGFG{staticvoidrotateMatrix(int[][]mat){intn=mat.length;// Swap elements from the start and end to// rotate by 180 degreesfor(inti=0;i<n/2;i++){for(intj=0;j<n;j++){inttemp=mat[i][j];mat[i][j]=mat[n-i-1][n-j-1];mat[n-i-1][n-j-1]=temp;}}// Handle the middle row if the matrix // has odd dimensionsif(n%2!=0){intmid=n/2;for(intj=0;j<n/2;j++){inttemp=mat[mid][j];mat[mid][j]=mat[mid][n-j-1];mat[mid][n-j-1]=temp;}}}publicstaticvoidmain(String[]args){int[][]mat={{1,2,3},{4,5,6},{7,8,9}};rotateMatrix(mat);for(int[]row:mat){for(intx:row){System.out.print(x+" ");}System.out.println();}}}
Python
defrotateMatrix(mat):n=len(mat)# Swap elements from the start and end to# rotate by 180 degreesforiinrange(n//2):forjinrange(n):mat[i][j],mat[n-i-1][n-j-1]= \
mat[n-i-1][n-j-1],mat[i][j]# Handle the middle row if the matrix # has odd dimensionsifn%2!=0:mid=n//2forjinrange(n//2):mat[mid][j],mat[mid][n-j-1]= \
mat[mid][n-j-1],mat[mid][j]if__name__=="__main__":mat=[[1,2,3],[4,5,6],[7,8,9]]rotateMatrix(mat)forrowinmat:print(" ".join(map(str,row)))
C#
usingSystem;classGFG{staticvoidrotateMatrix(int[,]mat){intn=mat.GetLength(0);// Swap elements from the start and end to// rotate by 180 degreesfor(inti=0;i<n/2;i++){for(intj=0;j<n;j++){inttemp=mat[i,j];mat[i,j]=mat[n-i-1,n-j-1];mat[n-i-1,n-j-1]=temp;}}// Handle the middle row if the matrix // has odd dimensionsif(n%2!=0){intmid=n/2;for(intj=0;j<n/2;j++){inttemp=mat[mid,j];mat[mid,j]=mat[mid,n-j-1];mat[mid,n-j-1]=temp;}}}staticvoidMain(){int[,]mat={{1,2,3},{4,5,6},{7,8,9}};rotateMatrix(mat);intn=mat.GetLength(0);for(inti=0;i<n;i++){for(intj=0;j<n;j++){Console.Write(mat[i,j]+" ");}Console.WriteLine();}}}
JavaScript
functionrotateMatrix(mat){constn=mat.length;// Swap elements from the start and end to// rotate by 180 degreesfor(leti=0;i<n/2;i++){for(letj=0;j<n;j++){[mat[i][j],mat[n-i-1][n-j-1]]=[mat[n-i-1][n-j-1],mat[i][j]];}}// Handle the middle row if the matrix // has odd dimensionsif(n%2!==0){constmid=Math.floor(n/2);for(letj=0;j<n/2;j++){[mat[mid][j],mat[mid][n-j-1]]=[mat[mid][n-j-1],mat[mid][j]];}}}// Driver codeconstmat=[[1,2,3],[4,5,6],[7,8,9]];rotateMatrix(mat);mat.forEach(row=>console.log(row.join(" ")));