Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# 2d array rotation

Posted on 2011-03-23
Medium Priority
5,044 Views
how to rotate a 2d array (matrix) 90 degrees anticlockwise so:

X =
1    2    3
4    5    6
7    8    9

becomes

Y =
3    6    9
2    5    8
1    4    7
0
Question by:chudyksg
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 40

Expert Comment

ID: 35198684
create another empty array of 3x3 dimension, and follow these steps

pick value at 1,1 and put it at 3,1
pick value at 1,2 and put it at 2,1
pick value at 1,3 and put it at 1,1
pick value at 2,1 and put it at 3,2
pick value at 2,3 and put it at 1,2
pick value at 3,1 and put it at 3,3
pick value at 3,2 and put it at 2,3
pick value at 3,3 and put it at 1,3
0

LVL 28

Accepted Solution

rrz earned 2000 total points
ID: 35200226
from
http://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array
``````public int[][] rotateMatrixLeft(int[][] matrix)
{
/* W and H are already swapped */
int w = matrix.length;
int h = matrix[0].length;
int[][] ret = new int[h][w];
for (int i = 0; i < h; ++i) {
for (int j = 0; j < w; ++j) {
ret[i][j] = matrix[j][h - i - 1];
}
}
return ret;
}
``````
0

Expert Comment

ID: 35205990
This will rotate any matrix 90 degrees anti-clock.

``````/**
* To rotate the array 90 degrees anti-clock wise. This will rotate square
* and non square matrix.
*
* @param sourceArray
* @return
*/
public int[][] antiClock90Rotation(int[][] sourceArray) {
int[][] rotatedArray = new int[sourceArray[0].length][sourceArray.length];
int positionFactor = rotatedArray.length - 1;
for (int i = 0; i < rotatedArray.length; i++) {
for (int j = 0; j < rotatedArray[i].length; j++) {
int a = i - positionFactor;
a = (a < 0) ? -a : a;
rotatedArray[i][j] = sourceArray[j][a];
}
}
return rotatedArray;
}
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.