Statementâ–¼
Given an n×n matrix, rotate the matrix 90 degrees clockwise. The performed rotation should be in place, i.e., the given matrix is modified directly without allocating another matrix.
Note: The function should only return the modified input matrix.
Constraints:
matrix.length
=matrix[i].length
- 1≤
matrix.length
≤20 - −103≤
matrix[i][j]
≤103
Solution
The idea is to make groups of four cells and rotate them by 90 degrees clockwise.
Here’s how the algorithm works:
-
We run a loop where
row
ranges from0
ton / 2
.-
Within this loop, we run a nested loop where
col
ranges fromrow
ton - row - 1
. These loops traverse the groups of four cells in the matrix. In this nested loop, we perform three swaps:-
The value of the top-left cell is swapped with the value of the top-right cell.
-
The value of the top-left cell is swapped with the value of the bottom-right cell.
-
The value of the top-left cell is swapped with the value of the bottom-left cell.
-
-
The current group of four cells has been rotated by 90 degrees. We now move to the next iteration of the outer loop to rotate the next group.
-
-
We repeat the process above until the whole matrix has been rotated.
Let’s look at the following illustration to get a better understanding of the solution: