I have an non-square array like this:
const int dim1 = 3, dim2 = 4;
int array[12] = { 1, 2, 3,
4, 5, 6,
7, 8, 9,
10,11,12};
and I need to convert it to:
{3,6,9,12,
2,5,8,11,
1,4,7,10}
that is, rotate/shuffle it counter-clockwise (or clockwise, the algorithm should be similiar).
The algorithm should use a minimal amount of space. I have to rotate an image in an extremely memory-constrained environment, so the less space the better. Speed is not as big an issue.
Rotate Matrix 90 Degree Clockwise or Right Rotation The rotation of a matrix involves two steps: First, find the transpose of the given matrix. Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.
The formula of this rotation is : RM[x + y - 1][n - x + y] = M[x][y], where RM means rotated matrix, M the initial matrix, and n the dimension of the initial matrix (which is n x n).
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.
You can transpose the matrix in-place (see http://en.wikipedia.org/wiki/In-place_matrix_transposition) and then reverse the rows which is trivial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With