Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate a matrix 90 degrees without using any extra space? [duplicate]

Possible Duplicate:
Algorithm to rotate an image 90 degrees in place? (No extra memory)

By saying 90 degrees i mean to say if:

A = {1,2,3,      4,5,6,      7,8,9} 

then after 90 degree rotation A becomes:

A = {7,4,1,      8,5,2,      9,6,3} 
like image 407
Vaibhav Avatar asked Aug 15 '10 18:08

Vaibhav


People also ask

How do you rotate a matrix 90 degrees anticlockwise in Java?

Approach to solve this problem Take Input of a square matrix. Find the transpose of the matrix. Swap the element at index 0 with index n-1. Return the output.

How do you rotate points 90 degrees?

90 Degree Rotation When rotating a point 90 degrees counterclockwise about the origin our point A(x,y) becomes A'(-y,x). In other words, switch x and y and make y negative.


1 Answers

Transpose and interchange rows or columns (depends whether you want to rotate left or right).

e. g.

1) original matrix  1 2 3 4 5 6 7 8 9  2) transpose  1 4 7 2 5 8 3 6 9  3-a) change rows to rotate left  3 6 9 2 5 8 1 4 7  3-b) or change columns to rotate right  7 4 1 8 5 2 9 6 3 

All these operations can be done without allocating memory.

like image 64
Narek Avatar answered Sep 21 '22 08:09

Narek