How can I rotate matrix
|3 4 5 6 8|
|5 4 3 2 6|
|3 3 7 8 9|
to
|8 6 9|
|6 2 8|
|5 3 7|
|4 4 3|
|3 5 3|
Because all algorithms I've seen was for N*N matrix.
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.
To do this we'll first make a function that takes in a matrix, or an array of array, and a direction to tell us which way to rotate. Before we begin, lets make an empty array that will hold the values of rotated values. var rotateMatrix = function(matrix, direction ) { let rotated = []; return rotated; };
The rule for a rotation by 90° about the origin is (x,y)→(−y,x) .
If your matrix is represented by an array matrix[i, j]
, where the i
are the rows and the j
are the columns, then implement the following method:
static int[,] RotateMatrixCounterClockwise(int[,] oldMatrix)
{
int[,] newMatrix = new int[oldMatrix.GetLength(1), oldMatrix.GetLength(0)];
int newColumn, newRow = 0;
for (int oldColumn = oldMatrix.GetLength(1) - 1; oldColumn >= 0; oldColumn--)
{
newColumn = 0;
for (int oldRow = 0; oldRow < oldMatrix.GetLength(0); oldRow++)
{
newMatrix[newRow, newColumn] = oldMatrix[oldRow, oldColumn];
newColumn++;
}
newRow++;
}
return newMatrix;
}
This works for matrices of all sizes.
Edit: If this operation is too expensive, then one could try changing the way one reads the matrix instead of changing the matrix itself. For example, if I am displaying the matrix as follows:
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}
then I could represent a 90-degree counterclockwise rotation by changing the way I read the matrix:
for (int col = matrix.GetLength(1) - 1; col >= 0; col--)
{
for (int row = 0; row < matrix.GetLength(0); row++)
{
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}
This access pattern could be abstracted in a class, too.
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