Reputation: 11159
Given a 4x4 matrix, what formula could i apply to each (x,y) cell to yield an (x,y) if the matrix was rotated 90 degrees to the right? I tried iterating over each cell but different cells gave different formulas.
Given the following matrix of values.
0| | | | |
1| | | | |
2| | | | |
3| | | | |
-------------
0 1 2 3
Rotate the values 90 degrees by moving the value in (x,y) to the (x,y) value in the matching cell using the matrix below:
0 | 0,3 | 0,2 | 0,1 | 0,0 |
1 | 1,3 | 1,2 | 1,1 | 1,0 |
2 | 2,3 | 2,2 | 2,1 | 2,0 |
3 | 3,3 | 3,2 | 3,1 | 3,0 |
--------------------------
0 1 2 3
ie:
If cell (0,0) has the value 5,
using the translation matrix 5 would move to (3,0).
Hard-coding this translation matrix is tedious and error prone, and if the matrix size grows to huge numbers doing this by hand is simply retarded.
Upvotes: 1
Views: 967
Reputation: 34034
If you have an n
by n
matrix, assuming (i, j)
means the i
th row and the j
th column, for a rotation to the right:
the cell (i, j) will move to (j, n-i)
Here's how you think about it. Picture the entire i
th row. When you rotate the matrix, that entire row turns into an entire column. Which one? It'll be i
columns from the right, i.e., column n-i
.
Now picture the entire j
th column. When you rotate, the column turns into row. Which one? It'll be j
rows from the top, i.e., row j
.
Upvotes: 3
Reputation: 14521
Heres an example with C code
http://bytes.com/topic/c/answers/516008-rotate-matrix-any-size
Upvotes: 0