Problem · Matrix
Rotate a Square Matrix Clockwise
Learn this problemProblem statement
You are given an n x n integer matrix. Return a new matrix obtained by rotating the input exactly 90 degrees clockwise.
The returned cell at row r and column c must contain the original value from row n - 1 - c and column r. You do not need to mutate the input matrix.
Function
rotateSquareMatrixClockwise(matrix: int[][]) → int[][]Examples
Example 1
matrix = [[1,2,3],[4,5,6],[7,8,9]]return = [[7,4,1],[8,5,2],[9,6,3]]The first column becomes the first row in reverse order, and the same rule applies to every column.
Example 2
matrix = [[5]]return = [[5]]A one-cell matrix is unchanged by rotation.
Example 3
matrix = [[-1,2],[3,4]]return = [[3,-1],[4,2]]The transformation preserves every signed value while moving it to its clockwise position.
Constraints
1 <= n <= 500.matrix.length = nand every row has lengthn.- Every matrix value is a signed 32-bit integer.