matrix
arrays
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees clockwise and return the rotated matrix. The judge checks the returned matrix, so you may build a new matrix or rotate in place and return it either way.
Input / output
- Input:
matrix: integer[][], always square (n x n) - Output:
integer[][], the same matrix rotated 90 degrees clockwise
Examples
matrix = [[1,2,3],[4,5,6],[7,8,9]]returns[[7,4,1],[8,5,2],[9,6,3]].matrix = [[1,2],[3,4]]returns[[3,1],[4,2]].matrix = [[1]]returns[[1]].
Constraints
n == matrix.length == matrix[i].length1 <= n <= 20-1,000 <= matrix[i][j] <= 1,000
Follow-up Can you rotate the matrix in place using only O(1) extra space, by first transposing and then reversing each row?
Examples
Example 1 (3x3)
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
Example 2 (2x2)
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]
Example 3 (1x1)
Input: matrix = [[1]]
Output: [[1]]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.