You can rotate a matrix 90 degrees clockwise. In programming, this is a common question in coding interviews because it tests your ability to work with multi-dimensional arrays.
To achieve this, you just need to understand the pattern. When a matrix is rotated 90 degrees, the first row becomes the last column, the second row becomes the second last column, and so on.
There are several methods to achieve this task and here is a simple and intuitive method using extra space.
Let’s say we have a matrix ‘m‘ and its dimensions are ‘n‘x‘n‘. We start from the top row, we take the elements of the top row and place them in the last column in the same order. We take the elements from the second row and place them in the second last column in the same order and so on.
Here’s the pseudocode for the process:
Let A be the original matrix
Let n be the dimension of the matrix
Let B be a new n x n matrix
For i from 0 to n-1
For j from 0 to n-1
B[j][n-1-i] = A[i][j]
Here’s how it works on a 3x3 matrix for example:
Suppose A is:
A = 1 2 3
4 5 6
7 8 9
The rotated matrix B is:
B = 7 4 1
8 5 2
9 6 3
For any element A[i][j] in the original matrix, it will go to position B[j][n - 1 - i] in the rotated matrix.
If you need to rotate the matrix in-place (without allocating extra space), the solution is a bit more complex as you need to do the rotation in a cycle-wise manner. That is often the follow-up question in coding interviews.