Given a square n x n matrix, return a new matrix that results from:
- Transposing the matrix:
matrix[i][j]becomesmatrix[j][i]. - Rotating the matrix 90 degrees clockwise.
Example:
-
Input:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] -
Transpose Output:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]] -
Rotate 90° Output:
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
In-place Rotation (Common Follow-up):
To rotate the matrix in-place (without allocating a new n x n matrix), you can perform two steps:
- Transpose the matrix (swap
matrix[i][j]withmatrix[j][i]). - Reverse each row.
1
2
3
4
5
6
7
8
9
step=Start
Step 1 / 9
Step 1:
Start with the original matrix. We will perform In-place Rotation: Transpose then Reverse Rows.
Focus: default
step="Start"