Rotate Matrix
easySave
ArrayMatrix
Given a square matrix (2D array), rotate the matrix by 90 degrees clockwise. You have to modify the matrix in place, which means you should not use any additional space for another matrix.
Example 1
Input
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Output
[[7,4,1],[8,5,2],[9,6,3]]
Explanation. The matrix is rotated 90 degrees clockwise.
Example 2
Input
[ [ 1 ] ]
Output
[[1]]
Explanation. A 1x1 matrix remains the same when it is rotated.
Example 3
Input
[ [ 1, 2 ], [ 3, 4 ] ]
Output
[[3,1],[4,2]]
Explanation. The 2x2 matrix is rotated 90 degrees clockwise resulting in the elements being rearranged accordingly.
Follow-up: Can you perform the rotation in a single pass of the matrix?
Constraints:
The matrix will have at least one row and one column (1x1 up to 10x10). All elements in the matrix will be integers.
- Views
- 3