Rotate a matrix by 90 degree without using any extra space | Set 2
Last Updated :
07 Nov, 2023
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.
Examples:
Input:
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7
Rotated the input matrix by
90 degrees in anti-clockwise direction.
Input:
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
Rotated the input matrix by
90 degrees in anti-clockwise direction.
An approach that requires extra space is already discussed in a different article:
Inplace rotate square matrix by 90 degrees | Set 1
This post discusses the same problem with a different approach which is space-optimized.
Approach: The idea is to find the transpose of the matrix and then reverse the columns of the transposed matrix.
Here is an example to show how this works.
Algorithm:
- To solve the given problem there are two tasks. 1st is finding the transpose and the second is reversing the columns without using extra space
- A transpose of a matrix is when the matrix is flipped over its diagonal, i.e the row index of an element becomes the column index and vice versa. So to find the transpose interchange of the elements at position (i, j) with (j, i). Run two loops, the outer loop from 0 to row count and the inner loop from 0 to the index of the outer loop.
- To reverse the column of the transposed matrix, run two nested loops, the outer loop from 0 to column count and the inner loop from 0 to row count/2, interchange elements at (i, j) with (i, row[count-1-j]), where i and j are indices of inner and outer loop respectively.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
void reverseColumns( int arr[R][C])
{
for ( int i = 0; i < C; i++)
for ( int j = 0, k = C - 1; j < k; j++, k--)
swap(arr[j][i], arr[k][i]);
}
void transpose( int arr[R][C])
{
for ( int i = 0; i < R; i++)
for ( int j = i; j < C; j++)
swap(arr[i][j], arr[j][i]);
}
void printMatrix( int arr[R][C])
{
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; j++)
cout << arr[i][j] << " " ;
cout << '\n' ;
}
}
void rotate90( int arr[R][C])
{
transpose(arr);
reverseColumns(arr);
}
int main()
{
int arr[R][C] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotate90(arr);
printMatrix(arr);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void reverseColumns( int arr[][])
{
for ( int i = 0 ; i < arr[ 0 ].length; i++)
for ( int j = 0 , k = arr[ 0 ].length - 1 ; j < k;
j++, k--) {
int temp = arr[j][i];
arr[j][i] = arr[k][i];
arr[k][i] = temp;
}
}
static void transpose( int arr[][])
{
for ( int i = 0 ; i < arr.length; i++)
for ( int j = i; j < arr[ 0 ].length; j++) {
int temp = arr[j][i];
arr[j][i] = arr[i][j];
arr[i][j] = temp;
}
}
static void printMatrix( int arr[][])
{
for ( int i = 0 ; i < arr.length; i++) {
for ( int j = 0 ; j < arr[ 0 ].length; j++)
System.out.print(arr[i][j] + " " );
System.out.println( "" );
}
}
static void rotate90( int arr[][])
{
transpose(arr);
reverseColumns(arr);
}
public static void main(String[] args)
{
int arr[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 },
{ 13 , 14 , 15 , 16 } };
rotate90(arr);
printMatrix(arr);
}
}
|
Python3
R = 4
C = 4
def reverseColumns(arr):
for i in range (C):
j = 0
k = C - 1
while j < k:
t = arr[j][i]
arr[j][i] = arr[k][i]
arr[k][i] = t
j + = 1
k - = 1
def transpose(arr):
for i in range (R):
for j in range (i, C):
t = arr[i][j]
arr[i][j] = arr[j][i]
arr[j][i] = t
def printMatrix(arr):
for i in range (R):
for j in range (C):
print ( str (arr[i][j]), end = " " )
print ()
def rotate90(arr):
transpose(arr)
reverseColumns(arr)
arr = [[ 1 , 2 , 3 , 4 ],
[ 5 , 6 , 7 , 8 ],
[ 9 , 10 , 11 , 12 ],
[ 13 , 14 , 15 , 16 ]
]
rotate90(arr)
printMatrix(arr)
|
C#
using System;
class GFG {
static int R = 4;
static int C = 4;
static void reverseColumns( int [, ] arr)
{
for ( int i = 0; i < C; i++)
for ( int j = 0, k = C - 1; j < k; j++, k--) {
int temp = arr[j, i];
arr[j, i] = arr[k, i];
arr[k, i] = temp;
}
}
static void transpose( int [, ] arr)
{
for ( int i = 0; i < R; i++)
for ( int j = i; j < C; j++) {
int temp = arr[j, i];
arr[j, i] = arr[i, j];
arr[i, j] = temp;
}
}
static void printMatrix( int [, ] arr)
{
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; j++)
Console.Write(arr[i, j] + " " );
Console.WriteLine( "" );
}
}
static void rotate90( int [, ] arr)
{
transpose(arr);
reverseColumns(arr);
}
static void Main()
{
int [, ] arr = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotate90(arr);
printMatrix(arr);
}
}
|
Javascript
<script>
function reverseColumns(arr)
{
for (let i = 0; i < arr[0].length; i++)
for (let j = 0, k = arr[0].length - 1;
j < k; j++, k--) {
let temp = arr[j][i];
arr[j][i] = arr[k][i];
arr[k][i] = temp;
}
}
function transpose(arr)
{
for (let i = 0; i < arr.length; i++)
for (let j = i; j < arr[0].length;
j++) {
let temp = arr[j][i];
arr[j][i] = arr[i][j];
arr[i][j] = temp;
}
}
function printMatrix(arr)
{
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[0].length;
j++)
document.write(arr[i][j] + " " );
document.write( "<br>" );
}
}
function rotate90(arr)
{
transpose(arr);
reverseColumns(arr);
}
let arr = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
rotate90(arr)
printMatrix(arr)
</script>
|
PHP
<?php
$R = 4;
$C = 4;
function reverseColumns(& $arr )
{
global $C ;
for ( $i = 0; $i < $C ; $i ++)
{
for ( $j = 0, $k = $C - 1; $j < $k ; $j ++, $k --)
{
$t = $arr [ $j ][ $i ];
$arr [ $j ][ $i ] = $arr [ $k ][ $i ];
$arr [ $k ][ $i ] = $t ;
}
}
}
function transpose(& $arr )
{
global $R , $C ;
for ( $i = 0; $i < $R ; $i ++)
{
for ( $j = $i ; $j < $C ; $j ++)
{
$t = $arr [ $i ][ $j ];
$arr [ $i ][ $j ] = $arr [ $j ][ $i ];
$arr [ $j ][ $i ] = $t ;
}
}
}
function printMatrix(& $arr )
{
global $R , $C ;
for ( $i = 0; $i < $R ; $i ++) {
for ( $j = 0; $j < $C ; $j ++)
echo $arr [ $i ][ $j ]. " " ;
echo "\n" ;
}
}
function rotate90(& $arr )
{
transpose( $arr );
reverseColumns( $arr );
}
$arr = array ( array ( 1, 2, 3, 4 ),
array ( 5, 6, 7, 8 ),
array ( 9, 10, 11, 12 ),
array ( 13, 14, 15, 16 ) );
rotate90( $arr );
printMatrix( $arr );
return 0;
?>
|
Output
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Complexity Analysis:
- Time Complexity: O(R*C).
The matrix is traversed twice, so the complexity is O(R*C).
- Auxiliary Space: O(1).
The space complexity is constant as no extra space is required.
Another Approach using a single traversal of the matrix :
The idea is to traverse along the boundaries of the matrix and shift the positions of the elements in 900 anticlockwise directions in each boundary. There are such (n/2-1) boundaries in the matrix.
Algorithm:
- Iterate over all the boundaries in the matrix. There are total (n/2-1) boundaries
- For each boundary take the 4 corner elements and swap them such that the 4 corner elements get rotated in anticlockwise directions. Then take the next 4 elements along the edges(left, right, top, bottom) and swap them in an anticlockwise direction. Continue as long as all the elements in that particular boundary get rotated in 900 anticlockwise directions.
- Then move on to the next inner boundary and continue the process as long the whole matrix is rotated in 900 anticlockwise direction.
Original array
total n/2-1 boundaries
for outermost boundary
for next inner boundary
Implementation:
C++14
#include <bits/stdc++.h>
using namespace std;
#define R 4
#define C 4
void rotateby90( int arr[R][C])
{
int n = R;
int a = 0, b = 0, c = 0, d = 0;
for ( int i = 0; i <= n / 2 - 1; i++) {
for ( int j = 0; j <= n - 2 * i - 2; j++) {
a = arr[i + j][i];
b = arr[n - 1 - i][i + j];
c = arr[n - 1 - i - j][n - 1 - i];
d = arr[i][n - 1 - i - j];
arr[i + j][i] = d;
arr[n - 1 - i][i + j] = a;
arr[n - 1 - i - j][n - 1 - i] = b;
arr[i][n - 1 - i - j] = c;
}
}
}
void printMatrix( int arr[R][C])
{
for ( int i = 0; i < R; i++) {
for ( int j = 0; j < C; j++)
cout << arr[i][j] << " " ;
cout << '\n' ;
}
}
int main()
{
int arr[R][C] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotateby90(arr);
printMatrix(arr);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void rotateby90( int arr[][])
{
int n = arr.length;
int a = 0 , b = 0 , c = 0 , d = 0 ;
for ( int i = 0 ; i <= n / 2 - 1 ; i++) {
for ( int j = 0 ; j <= n - 2 * i - 2 ; j++) {
a = arr[i + j][i];
b = arr[n - 1 - i][i + j];
c = arr[n - 1 - i - j][n - 1 - i];
d = arr[i][n - 1 - i - j];
arr[i + j][i] = d;
arr[n - 1 - i][i + j] = a;
arr[n - 1 - i - j][n - 1 - i] = b;
arr[i][n - 1 - i - j] = c;
}
}
}
static void printMatrix( int arr[][])
{
for ( int i = 0 ; i < arr.length; i++) {
for ( int j = 0 ; j < arr[ 0 ].length; j++)
System.out.print(arr[i][j] + " " );
System.out.println( "" );
}
}
public static void main(String[] args)
{
int arr[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 },
{ 13 , 14 , 15 , 16 } };
rotateby90(arr);
printMatrix(arr);
}
}
|
Python3
def rotateby90(arr):
n = len (arr)
a,b,c,d = 0 , 0 , 0 , 0
for i in range (n / / 2 ):
for j in range (n - 2 * i - 1 ):
a = arr[i + j][i]
b = arr[n - 1 - i][i + j]
c = arr[n - 1 - i - j][n - 1 - i]
d = arr[i][n - 1 - i - j]
arr[i + j][i] = d
arr[n - 1 - i][i + j] = a
arr[n - 1 - i - j][n - 1 - i] = b
arr[i][n - 1 - i - j] = c
def printMatrix(arr):
for i in range ( len (arr)):
for j in range ( len (arr[ 0 ])):
print (arr[i][j] ,end = " " )
print ()
arr = [[ 1 , 2 , 3 , 4 ],
[ 5 , 6 , 7 , 8 ],
[ 9 , 10 , 11 , 12 ],
[ 13 , 14 , 15 , 16 ]]
rotateby90(arr)
printMatrix(arr)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static void rotateby90( int [,]arr)
{
int n = arr.GetLength(0);
int a = 0, b = 0, c = 0, d = 0;
for ( int i = 0; i <= n / 2 - 1; i++) {
for ( int j = 0; j <= n - 2 * i - 2; j++) {
a = arr[i + j,i];
b = arr[n - 1 - i,i + j];
c = arr[n - 1 - i - j,n - 1 - i];
d = arr[i,n - 1 - i - j];
arr[i + j,i] = d;
arr[n - 1 - i,i + j] = a;
arr[n - 1 - i - j,n - 1 - i] = b;
arr[i,n - 1 - i - j] = c;
}
}
}
static void printMatrix( int [,]arr)
{
for ( int i = 0; i < arr.GetLength(0); i++) {
for ( int j = 0; j < arr.GetLength(1); j++)
Console.Write(arr[i,j] + " " );
Console.WriteLine( "" );
}
}
public static void Main(String[] args)
{
int [,]arr = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotateby90(arr);
printMatrix(arr);
}
}
|
Javascript
<script>
function rotateby90(arr)
{
let n = arr.length;
let a = 0, b = 0, c = 0, d = 0;
for (let i = 0; i <= n / 2 - 1; i++) {
for (let j = 0; j <= n - 2 * i - 2; j++) {
a = arr[i + j][i];
b = arr[n - 1 - i][i + j];
c = arr[n - 1 - i - j][n - 1 - i];
d = arr[i][n - 1 - i - j];
arr[i + j][i] = d;
arr[n - 1 - i][i + j] = a;
arr[n - 1 - i - j][n - 1 - i] = b;
arr[i][n - 1 - i - j] = c;
}
}
}
function printMatrix(arr)
{
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[0].length; j++)
document.write(arr[i][j] + " " );
document.write( "<br>" );
}
}
let arr=[[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ]];
rotateby90(arr);
printMatrix(arr);
</script>
|
Output
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Complexity Analysis:
Time Complexity: O(R*C). The matrix is traversed only once, so the time complexity is O(R*C).
Auxiliary Space: O(1). The space complexity is O(1) as no extra space is required.
Implementation: Let’s see a method of Python numpy that can be used to arrive at the particular solution.
C++
#include <iostream>
#include <vector>
std::vector<std::vector< int >> flipMatrixAntiClockwise( const std::vector<std::vector< int >>& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
std::vector<std::vector< int >> result(cols, std::vector< int >(rows, 0));
for ( int i = 0; i < rows; i++) {
for ( int j = 0; j < cols; j++) {
result[j][rows - i - 1] = matrix[i][j];
}
}
return result;
}
int main() {
std::vector<std::vector< int >> arr = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
std::vector<std::vector< int >> flippedMatrix = flipMatrixAntiClockwise(arr);
std::cout << "nnumpy implementation " << std::endl;
for ( const auto & row : flippedMatrix) {
for ( int value : row) {
std::cout << value << ' ' ;
}
std::cout << std::endl;
}
return 0;
}
|
Java
import java.util.Arrays;
public class MatrixFlipAntiClockwise {
public static int [][] flipMatrixAntiClockwise( int [][] matrix) {
int rows = matrix.length;
int cols = matrix[ 0 ].length;
int [][] result = new int [cols][rows];
for ( int i = 0 ; i < rows; i++) {
for ( int j = 0 ; j < cols; j++) {
result[j][rows - i - 1 ] = matrix[i][j];
}
}
return result;
}
public static void main(String[] args) {
int [][] arr = {
{ 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 },
{ 13 , 14 , 15 , 16 }
};
int [][] flippedMatrix = flipMatrixAntiClockwise(arr);
System.out.println( "Java implementation" );
for ( int [] row : flippedMatrix) {
for ( int value : row) {
System.out.print(value + " " );
}
System.out.println();
}
}
}
|
Python3
import numpy
arr = [[ 1 , 2 , 3 , 4 ],
[ 5 , 6 , 7 , 8 ],
[ 9 , 10 , 11 , 12 ],
[ 13 , 14 , 15 , 16 ]
]
def flip(m, axis):
if not hasattr (m, 'ndim' ):
m = asarray(m)
indexer = [ slice ( None )] * m.ndim
try :
indexer[axis] = slice ( None , None , - 1 )
except IndexError:
raise ValueError( "axis =% i is invalid for the % i-dimensional input array"
% (axis, m.ndim))
return m[ tuple (indexer)]
trans = numpy.transpose(arr)
flipmat = flip(trans, 0 )
print ( "\nnumpy implementation\n" )
print (flipmat)
|
C#
using System;
using System.Collections.Generic;
class Program
{
static List<List< int >> FlipMatrixAntiClockwise(List<List< int >> matrix)
{
int rows = matrix.Count;
int cols = matrix[0].Count;
List<List< int >> result = new List<List< int >>();
for ( int i = 0; i < cols; i++)
{
result.Add( new List< int >( new int [rows]));
}
for ( int i = 0; i < rows; i++)
{
for ( int j = 0; j < cols; j++)
{
result[j][rows - i - 1] = matrix[i][j];
}
}
return result;
}
static void Main()
{
List<List< int >> arr = new List<List< int >>
{
new List< int > {1, 2, 3, 4},
new List< int > {5, 6, 7, 8},
new List< int > {9, 10, 11, 12},
new List< int > {13, 14, 15, 16}
};
List<List< int >> flippedMatrix = FlipMatrixAntiClockwise(arr);
Console.WriteLine( "C# implementation " );
foreach ( var row in flippedMatrix)
{
foreach ( int value in row)
{
Console.Write(value + " " );
}
Console.WriteLine();
}
}
}
|
Javascript
function flip(matrix, axis) {
if (!Array.isArray(matrix) || matrix.length === 0 || !Array.isArray(matrix[0])) {
throw new Error( "Invalid input matrix" );
}
const numRows = matrix.length;
const numCols = matrix[0].length;
const result = [];
for (let i = 0; i < numCols; i++) {
result[i] = [];
for (let j = 0; j < numRows; j++) {
result[i][j] = matrix[j][numCols - i - 1];
}
}
return result;
}
const arr = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
const trans = [];
for (let i = 0; i < arr[0].length; i++) {
trans[i] = [];
for (let j = 0; j < arr.length; j++) {
trans[i][j] = arr[j][i];
}
}
const flipmat = flip(trans, 0);
console.log( "\nnumpy implementation\n" );
for (let i = 0; i < flipmat.length; i++) {
console.log(flipmat[i].join( " " ));
}
|
Output:
numpy implementation
[[ 4 8 12 16]
[ 3 7 11 15]
[ 2 6 10 14]
[ 1 5 9 13]]
Note: The above steps/programs do left (or anticlockwise) rotation. Let’s see how to do the right rotation or clockwise rotation. The approach would be similar. Find the transpose of the matrix and then reverse the rows of the transposed matrix.
This is how it is done.
This article is contributed by DANISH_RAZA .
Rotating Along the Boundaries
We can start at the first 4 corners of the given matrix and then keep incrementing the row and column indices to moves around.
At any given moment we will have four corners lu (left-up),ld(left-down),ru(right-up),rd(right-down).
To left rotate we will first swap the ru and ld, then lu and ld and lastly ru and rd.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void rotateby90(vector<vector< int > >& matrix)
{
int n=matrix.size();
int mid;
if (n%2==0)
mid=n/2-1;
else
mid=n/2;
for ( int i=0,j=n-1;i<=mid;i++,j--)
{
for ( int k=0;k<j-i;k++)
{
swap(matrix[i][j-k],matrix[j][i+k]);
swap(matrix[i+k][i],matrix[j][i+k]);
swap(matrix[i][j-k],matrix[j-k][j]);
}
}
}
void printMatrix(vector<vector< int >>& arr)
{
int n=arr.size();
for ( int i=0;i<n;i++)
{
for ( int j=0;j<n;j++)
{
cout<<arr[i][j]<< " " ;
}
cout<<endl;
}
}
int main() {
vector<vector< int >> arr = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
rotateby90(arr);
printMatrix(arr);
return 0;
}
|
Java
import java.util.*;
class GFG{
private static int [][] swap( int [][] matrix, int x1, int x2, int y1, int y2) {
int temp = matrix[x1][x2] ;
matrix[x1][x2] = matrix[y1][y2];
matrix[y1][y2] = temp;
return matrix;
}
static int [][] rotateby90( int [][] matrix)
{
int n=matrix.length;
int mid;
if (n % 2 == 0 )
mid = n / 2 - 1 ;
else
mid = n / 2 ;
for ( int i = 0 , j = n - 1 ; i <= mid; i++, j--)
{
for ( int k = 0 ; k < j - i; k++)
{
matrix= swap(matrix, i, j - k, j, i + k);
matrix= swap(matrix, i + k, i, j, i + k);
matrix= swap(matrix, i, j - k, j - k, j);
}
}
return matrix;
}
static void printMatrix( int [][] arr)
{
int n = arr.length;
for ( int i = 0 ; i < n; i++)
{
for ( int j = 0 ; j < n; j++)
{
System.out.print(arr[i][j] + " " );
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] arr = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 },
{ 13 , 14 , 15 , 16 } };
arr = rotateby90(arr);
printMatrix(arr);
}
}
|
Python3
def rotateby90(arr):
n = len (arr)
if (n % 2 = = 0 ):
mid = n / / 2 - 1
else :
mid = n / 2
j = n - 1
for i in range (mid + 1 ):
for k in range (j - i):
arr[i][j - k],arr[j][i + k] = arr[j][i + k],arr[i][j - k]
arr[i + k][i],arr[j][i + k] = arr[j][i + k],arr[i + k][i]
arr[i][j - k],arr[j - k][j] = arr[j - k][j],arr[i][j - k]
j = j - 1
def printMatrix(arr):
for i in range ( len (arr)):
for j in range ( len (arr[ 0 ])):
print (arr[i][j] ,end = " " )
print ()
arr = [[ 1 , 2 , 3 , 4 ],
[ 5 , 6 , 7 , 8 ],
[ 9 , 10 , 11 , 12 ],
[ 13 , 14 , 15 , 16 ]]
rotateby90(arr)
printMatrix(arr)
|
C#
using System;
public class GFG{
private static int [,] swap( int [,] matrix, int x1, int x2, int y1, int y2) {
int temp = matrix[x1,x2] ;
matrix[x1,x2] = matrix[y1,y2];
matrix[y1,y2] = temp;
return matrix;
}
static int [,] rotateby90( int [,] matrix)
{
int n=matrix.GetLength(0);
int mid;
if (n % 2 == 0)
mid = (n / 2 - 1);
else
mid = (n / 2);
for ( int i = 0, j = n - 1; i <= mid; i++, j--)
{
for ( int k = 0; k < j - i; k++)
{
matrix= swap(matrix, i, j - k, j, i + k);
matrix= swap(matrix, i + k, i, j, i + k);
matrix= swap(matrix, i, j - k, j - k, j);
}
}
return matrix;
}
static void printMatrix( int [,] arr)
{
int n = arr.GetLength(0);
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < n; j++)
{
Console.Write(arr[i,j] + " " );
}
Console.WriteLine();
}
}
public static void Main(String[] args) {
int [,] arr = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 } };
arr = rotateby90(arr);
printMatrix(arr);
}
}
|
Javascript
<script>
function swap(matrix , x1 , x2 , y1 , y2) {
var temp = matrix[x1][x2];
matrix[x1][x2] = matrix[y1][y2];
matrix[y1][y2] = temp;
return matrix;
}
function rotateby90(matrix) {
var n = matrix.length;
var mid;
if (n % 2 == 0)
mid = n / 2 - 1;
else
mid = n / 2;
for (i = 0, j = n - 1; i <= mid; i++, j--) {
for (k = 0; k < j - i; k++) {
matrix = swap(matrix, i, j - k, j, i + k);
matrix = swap(matrix, i + k, i, j, i + k);
matrix = swap(matrix, i, j - k, j - k, j);
}
}
return matrix;
}
function printMatrix(arr) {
var n = arr.length;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
document.write(arr[i][j] + " " );
}
document.write( "<br/>" );
}
}
var arr = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ] ];
arr = rotateby90(arr);
printMatrix(arr);
</script>
|
Output
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Time Complexity: O(n2)
Auxiliary Space: O(1), since no extra space has been taken.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...