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.
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.
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.
The simplest way is to create another matrix, which has the dimensions N * M (if the original has M * N) and then use nested loops to copy values from one matrix to another... Just mind the correct index usage.