Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff.
[1][2][3][4]
[5][6][7][8]
[9][0][1][2]
[3][4][5][6]
Becomes:
[3][9][5][1]
[4][0][6][2]
[5][1][7][3]
[6][2][8][4]
Update: Nick's answer is the most straightforward, but is there a way to do it better than n^2? What if the matrix was 10000x10000?
O(n^2) time and O(1) space algorithm ( without any workarounds and hanky-panky stuff! )
Rotate by +90:
Rotate by -90:
Method 1 :
Method 2 :
Rotate by +180:
Method 1: Rotate by +90 twice
Method 2: Reverse each row and then reverse each column (Transpose)
Rotate by -180:
Method 1: Rotate by -90 twice
Method 2: Reverse each column and then reverse each row
Method 3: Rotate by +180 as they are same
#transpose is a standard method of Ruby's Array class, thus:
The implementation is an n^2 transposition function written in C. You can see it here: http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-transpose by choosing "click to toggle source" beside "transpose".
I recall better than O(n^2) solutions, but only for specially constructed matrices (such as sparse matrices)
Here's my Ruby version (note the values aren't displayed the same, but it still rotates as described).
The output:
Here is the Java version:
the method first rotate the mostouter layer, then move to the inner layer squentially.
C# code to rotate [n,m] 2D arrays 90 deg right
Result:
There are tons of good code here but I just want to show what's going on geometrically so you can understand the code logic a little better. Here is how I would approach this.
first of all, do not confuse this with transposition which is very easy..
the basica idea is to treat it as layers and we rotate one layer at a time..
say we have a 4x4
after we rotate it clockwise by 90 we get
so let's decompose this, first we rotate the 4 corners essentially
then we rotate the following diamond which is sort of askew
and then the 2nd skewed diamond
so that takes care of the outer edge so essentially we do that one shell at a time until
finally the middle square (or if it's odd just the final element which does not move)
so now let's figure out the indices of each layer, assume we always work with the outermost layer, we are doing
so on and so on until we are halfway through the edge
so in general the pattern is