Simple Matrix Rotation
Given a square matrix (2D array) of n x n dimensions, rotate it by 90 degrees in a clockwise direction without utilizing any extra space.
Example:
Input:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
Output:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Explanation. The matrix is rotated clockwise by 90 degrees, transforming each row into a column in reversed order.
[ [ 1 ] ]
Explanation. A 1x1 matrix rotated in any direction stays the same.
[ [ 1, 2 ], [ 3, 4 ] ]
Explanation. The 2x2 matrix rotates each row into a column in reversed position.
[ [ 5, 17, 4, 1 ], [ 2, 5, 0, 19 ], [ 15, 8, 7, 3 ], [ 9, 14, 12, 10 ] ]
Explanation. Every element has been moved according to a 90 degree clockwise rotation.
Follow-up: Can you extend this solution to handle the rotation of the matrix by 180 and 270 degrees as well?
1. The matrix will contain integer elements only. 2. The matrix dimensions will be n x n where n is at least 1 and at most 20.
- Accepted
- 1/1
- Acceptance Rate
- 100.0%
- Views
- 2