Inplace rotate square matrix by 90 degrees | Set 1
Last Updated :
21 Nov, 2023
Given a square matrix, turn it by 90 degrees in an anti-clockwise direction without using any extra space
Examples:
Input:
Matrix: 1 2 3
4 5 6
7 8 9
Output: 3 6 9
2 5 8
1 4 7
Input:
Matrix: 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output: 4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Note: An approach that requires extra space is already discussed here.
Example no1 – Inplace rotate square matrix by 90 degrees by forming cycles:
To solve the problem follow the below idea:
To solve the question without any extra space, rotate the array in form of squares, dividing the matrix into squares or cycles. For example,
A 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row, and 1st column. The second cycle is formed by the 2nd row, second-last column, second-last row, and 2nd column. The idea is for each square cycle, to swap the elements involved with the corresponding cell in the matrix in an anti-clockwise direction i.e. from top to left, left to bottom, bottom to right, and from right to top one at a time using nothing but a temporary variable to achieve this
Dry run of the above approach:
First Cycle:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Moving first group of four elements (elements
of 1st row, last row, 1st column and last column) of first cycle
in counter clockwise.
4 2 3 16
5 6 7 8
9 10 11 12
1 14 15 13
Moving next group of four elements of
first cycle in counter clockwise
4 8 3 16
5 6 7 15
2 10 11 12
1 14 9 13
Moving final group of four elements of
first cycle in counter clockwise
4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13
Second Cycle:
4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13
Fixing second cycle
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Follow the given steps to solve the problem:
- There are N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2 – 1, loop counter is i
- Consider elements in group of 4 in current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N – 2*i.
- So run a loop in each cycle from x to N – x – 1, loop counter is y
- The elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y) <- (y, N-1-x), (y, N-1-x)<- (N-1-x, N-1-y), (N-1-x, N-1-y)<- (N-1-y, x), (N-1-y, x)<- (x, y)
- Print the matrix.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define N 4
using namespace std;
void rotateMatrix( int mat[][N])
{
for ( int x = 0; x < N / 2; x++) {
for ( int y = x; y < N - x - 1; y++) {
int temp = mat[x][y];
mat[x][y] = mat[y][N - 1 - x];
mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y];
mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x];
mat[N - 1 - y][x] = temp;
}
}
}
void displayMatrix( int mat[N][N])
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++) {
cout << mat[i][j] << " " ;
}
cout << endl;
}
cout << endl;
}
int main()
{
int mat[N][N] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotateMatrix(mat);
displayMatrix(mat);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void rotateMatrix( int N, int mat[][])
{
for ( int x = 0 ; x < N / 2 ; x++) {
for ( int y = x; y < N - x - 1 ; y++) {
int temp = mat[x][y];
mat[x][y] = mat[y][N - 1 - x];
mat[y][N - 1 - x]
= mat[N - 1 - x][N - 1 - y];
mat[N - 1 - x][N - 1 - y]
= mat[N - 1 - y][x];
mat[N - 1 - y][x] = temp;
}
}
}
static void displayMatrix( int N, int mat[][])
{
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < N; j++)
System.out.print( " " + mat[i][j]);
System.out.print( "\n" );
}
System.out.print( "\n" );
}
public static void main(String[] args)
{
int N = 4 ;
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 },
{ 13 , 14 , 15 , 16 } };
rotateMatrix(N, mat);
displayMatrix(N, mat);
}
}
|
Python3
N = 4
def rotateMatrix(mat):
for x in range ( 0 , int (N / 2 )):
for y in range (x, N - x - 1 ):
temp = mat[x][y]
mat[x][y] = mat[y][N - 1 - x]
mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]
mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]
mat[N - 1 - y][x] = temp
def displayMatrix(mat):
for i in range ( 0 , N):
for j in range ( 0 , N):
print (mat[i][j], end = ' ' )
print ("")
if __name__ = = "__main__" :
mat = [[ 0 for x in range (N)] for y in range (N)]
mat = [[ 1 , 2 , 3 , 4 ],
[ 5 , 6 , 7 , 8 ],
[ 9 , 10 , 11 , 12 ],
[ 13 , 14 , 15 , 16 ]]
rotateMatrix(mat)
displayMatrix(mat)
|
C#
using System;
class GFG {
static void rotateMatrix( int N, int [, ] mat)
{
for ( int x = 0; x < N / 2; x++) {
for ( int y = x; y < N - x - 1; y++) {
int temp = mat[x, y];
mat[x, y] = mat[y, N - 1 - x];
mat[y, N - 1 - x]
= mat[N - 1 - x, N - 1 - y];
mat[N - 1 - x, N - 1 - y]
= mat[N - 1 - y, x];
mat[N - 1 - y, x] = temp;
}
}
}
static void displayMatrix( int N, int [, ] mat)
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++)
Console.Write( " " + mat[i, j]);
Console.WriteLine();
}
Console.WriteLine();
}
static public void Main()
{
int N = 4;
int [, ] mat = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotateMatrix(N, mat);
displayMatrix(N, mat);
}
}
|
Javascript
<script>
function rotateMatrix(N,mat)
{
for (let x = 0; x < N / 2; x++)
{
for (let y = x; y < N - x - 1; y++)
{
let temp = mat[x][y];
mat[x][y] = mat[y][N - 1 - x];
mat[y][N - 1 - x]
= mat[N - 1 - x][N - 1 - y];
mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x];
mat[N - 1 - y][x] = temp;
}
}
}
function displayMatrix(N,mat)
{
for (let i = 0; i < N; i++)
{
for (let j = 0; j < N; j++)
document.write(
" " + mat[i][j]);
document.write( "<br>" );
}
document.write( "<br>" );
}
let N = 4;
let mat=[[1, 2, 3, 4],[ 5, 6, 7, 8 ],[9, 10, 11, 12 ],[13, 14, 15, 16]];
rotateMatrix(N, mat);
displayMatrix(N, mat);
</script>
|
PHP
<?php
$N = 4;
function rotateMatrix(& $mat )
{
global $N ;
for ( $x = 0; $x < $N / 2; $x ++)
{
for ( $y = $x ;
$y < $N - $x - 1; $y ++)
{
$temp = $mat [ $x ][ $y ];
$mat [ $x ][ $y ] = $mat [ $y ][ $N - 1 - $x ];
$mat [ $y ][ $N - 1 - $x ] =
$mat [ $N - 1 - $x ][ $N - 1 - $y ];
$mat [ $N - 1 - $x ][ $N - 1 - $y ] =
$mat [ $N - 1 - $y ][ $x ];
$mat [ $N - 1 - $y ][ $x ] = $temp ;
}
}
}
function displayMatrix(& $mat )
{
global $N ;
for ( $i = 0; $i < $N ; $i ++)
{
for ( $j = 0; $j < $N ; $j ++)
echo $mat [ $i ][ $j ] . " " ;
echo "\n" ;
}
echo "\n" ;
}
$mat = array ( array (1, 2, 3, 4),
array (5, 6, 7, 8),
array (9, 10, 11, 12),
array (13, 14, 15, 16));
rotateMatrix( $mat );
displayMatrix( $mat );
?>
|
Output
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Time Complexity: O(N2), where n is the side of the array. A single traversal of the matrix is needed.
Auxiliary Space: O(1). As a constant space is needed
Example no 2 – Inplace rotate square matrix by 90 degrees by transposing and reversing the matrix:
Follow the given steps to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define N 4
void rotateMatrix( int mat[][N])
{
for ( int i = 0; i < N; i++)
reverse(mat[i], mat[i] + N);
for ( int i = 0; i < N; i++) {
for ( int j = i; j < N; j++)
swap(mat[i][j], mat[j][i]);
}
}
void displayMatrix( int mat[N][N])
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++) {
cout << mat[i][j] << " " ;
}
cout << endl;
}
cout << endl;
}
int main()
{
int mat[N][N] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotateMatrix(mat);
displayMatrix(mat);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void Reverse( int i, int mat[][], int N)
{
int start = 0 ;
int end = N - 1 ;
while (start < end) {
int temp = mat[i][start];
mat[i][start] = mat[i][end];
mat[i][end] = temp;
start++;
end--;
}
}
static void rotateMatrix( int N, int mat[][])
{
for ( int i = 0 ; i < N; i++)
Reverse(i, mat, N);
for ( int i = 0 ; i < N; i++) {
for ( int j = i; j < N; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
}
static void displayMatrix( int N, int mat[][])
{
for ( int i = 0 ; i < N; i++) {
for ( int j = 0 ; j < N; j++)
System.out.print( " " + mat[i][j]);
System.out.print( "\n" );
}
System.out.print( "\n" );
}
public static void main(String[] args)
{
int N = 4 ;
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 },
{ 13 , 14 , 15 , 16 } };
rotateMatrix(N, mat);
displayMatrix(N, mat);
}
}
|
Python3
def rotateMatrix(mat):
for i in range ( len (mat)):
mat[i].reverse()
for i in range ( len (mat)):
for j in range (i, len (mat)):
mat[i][j], mat[j][i] = mat[j][i], mat[i][j]
def displayMatrix(mat):
for i in range ( 0 , len (mat)):
for j in range ( 0 , len (mat)):
print (mat[i][j], end = ' ' )
print ()
if __name__ = = "__main__" :
mat = [[ 1 , 2 , 3 , 4 ],
[ 5 , 6 , 7 , 8 ],
[ 9 , 10 , 11 , 12 ],
[ 13 , 14 , 15 , 16 ]]
rotateMatrix(mat)
displayMatrix(mat)
|
C#
using System;
class GFG {
static void reverse( int N, int [, ] mat)
{
for ( int i = 0; i < N; i++) {
int start = 0;
int end = N - 1;
while (start < end) {
int temp = mat[i, start];
mat[i, start] = mat[i, end];
mat[i, end] = temp;
start++;
end--;
}
}
}
static void rotateMatrix( int N, int [, ] mat)
{
reverse(N, mat);
for ( int i = 0; i < N; i++) {
for ( int j = i; j < N; j++) {
int temp = mat[i, j];
mat[i, j] = mat[j, i];
mat[j, i] = temp;
}
}
}
static void displayMatrix( int N, int [, ] mat)
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++)
Console.Write(mat[i, j] + " " );
Console.Write( "\n" );
}
}
static public void Main()
{
int N = 4;
int [, ] mat = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotateMatrix(N, mat);
displayMatrix(N, mat);
}
}
|
Javascript
<script>
function rotateMatrix(mat){
for (let i = 0; i < mat.length; i++){
mat[i].reverse()
}
for (let i = 0; i < mat.length; i++){
for (let j = i; j < mat.length; j++){
let temp = mat[i][j]
mat[i][j] = mat[j][i]
mat[j][i] = temp
}
}
}
function displayMatrix(mat){
for (let i = 0; i < mat.length; i++){
for (let j = 0; j < mat.length; j++){
document.write(mat[i][j], ' ' )
}
document.write( "</br>" )
}
}
let mat = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
rotateMatrix(mat)
displayMatrix(mat)
</script>
|
Output
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Time Complexity: O(N2) + O(N2) where N is the size of the array.
Auxiliary Space: O(1). As a constant space is needed
Example no 3 – Implementation by using Vectors in c++
Input - Matrix
1 2 3
4 5 6
7 8 9
Algorithmic steps for implementation –
the algorithmic steps to in-place rotate a square matrix by 90 degrees:
- Transpose the matrix: For each element matrix[i][j] where i < j, swap it with the element matrix[j][i].
- Reverse each row of the matrix: For each row i of the matrix, reverse the order of the elements by swapping matrix[i][j] with matrix[i][n – j – 1] where n is the number of columns in the matrix.
- The matrix is now rotated by 90 degrees in place.
Note: The first step transforms the matrix into its transposed form, and the second step reverses the elements in each row, resulting in a rotation of the matrix by 90 degrees.
Program –
C++
#include <iostream>
#include <vector>
using namespace std;
void rotateMatrix(vector<vector< int >> &matrix) {
int n = matrix.size();
for ( int i = 0; i < n; i++) {
for ( int j = i; j < n; j++) {
swap(matrix[i][j], matrix[j][i]);
}
}
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n / 2; j++) {
swap(matrix[j][i], matrix[n - j - 1][i]);
}
}
}
int main() {
vector<vector< int >> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
rotateMatrix(matrix);
for ( int i = 0; i < matrix.size(); i++) {
for ( int j = 0; j < matrix[0].size(); j++) {
cout << matrix[i][j] << " " ;
}
cout << endl;
}
return 0;
}
|
Java
public class RotateMatrix {
public static void rotateMatrix( int [][] matrix)
{
int n = matrix.length;
for ( int i = 0 ; i < n; i++) {
for ( int j = i; j < n; j++) {
swap(matrix, i, j, j, i);
}
}
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < n / 2 ; j++) {
swap(matrix, j, i, n - j - 1 , i);
}
}
}
private static void swap( int [][] matrix, int i, int j,
int k, int l)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[k][l];
matrix[k][l] = temp;
}
public static void main(String[] args)
{
int [][] matrix
= { { 1 , 2 , 3 }, { 4 , 5 , 6 }, { 7 , 8 , 9 } };
rotateMatrix(matrix);
for ( int i = 0 ; i < matrix.length; i++) {
for ( int j = 0 ; j < matrix[ 0 ].length; j++) {
System.out.print(matrix[i][j] + " " );
}
System.out.println();
}
}
}
|
Python3
def rotateMatrix(matrix):
n = len (matrix)
for i in range (n):
for j in range (i,n):
temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
for i in range (n):
for j in range ( int (n / 2 )):
temp = matrix[n - j - 1 ][i]
matrix[n - j - 1 ][i] = matrix[j][i]
matrix[j][i] = temp
matrix = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
rotateMatrix(matrix)
for i in range ( len (matrix)):
for j in range ( len (matrix[ 0 ])):
print (matrix[i][j], end = " " )
print ("")
|
C#
using System;
using System.Collections.Generic;
class Gfg
{
static void RotateMatrix(List<List< int >> matrix)
{
int n = matrix.Count;
for ( int i = 0; i < n; i++)
{
for ( int j = i; j < n; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < n / 2; j++)
{
int temp = matrix[j][i];
matrix[j][i] = matrix[n - j - 1][i];
matrix[n - j - 1][i] = temp;
}
}
}
static void Main( string [] args)
{
List<List< int >> matrix = new List<List< int >> { new List< int > { 1, 2, 3 }, new List< int > { 4, 5, 6 }, new List< int > { 7, 8, 9 } };
RotateMatrix(matrix);
for ( int i = 0; i < matrix.Count; i++)
{
for ( int j = 0; j < matrix[0].Count; j++)
{
Console.Write(matrix[i][j] + " " );
}
Console.WriteLine();
}
Console.ReadLine();
}
}
|
Javascript
function rotateMatrix(matrix){
let n = matrix.length;
for (let i = 0; i<n; i++){
for (let j = i; j<n; j++){
let temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (let i = 0; i<n; i++){
for (let j = 0; j<n/2; j++){
temp = matrix[n - j - 1][i];
matrix[n - j - 1][i] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
rotateMatrix(matrix);
for (let i = 0; i<matrix.length; i++){
for (let j = 0; j<matrix[0].length; j++){
console.log(matrix[i][j] + " " );
}
console.log( "<br>" );
}
|
Explanation –
- In this implementation, the rotateMatrix function takes a 2D vector matrix as input and rotates the matrix by 90 degrees in the anticlockwise direction in place.
The first step is to transpose the matrix, which is done by swapping the elements matrix[i][j] and matrix[j][i] for i < j.
The second step is to reverse each column of the matrix, which is done by swapping the elements matrix[j][i] and matrix[n – j – 1][i] where n is the number of rows in the matrix.
- The time complexity of this algorithm is O(n^2), where n is the number of rows (and columns) in the matrix. This is because the algorithm performs a constant amount of work for each element in the matrix.
- The Auxiliary Space needed for this algorithm is O(1), since no extra space is used.
Exercise: Turn the 2D matrix by 90 degrees in a clockwise direction without using extra space.
Rotate a matrix by 90 degrees without using any extra space | Set 2
This article is contributed by Aditya Goel.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...