Description
You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees clockwise. You have to rotate the image in-place.
Examples
matrix = [[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]]In a 90-degree clockwise rotation, each element at (row, col) moves to (col, n-1-row). The first column [1,4,7] becomes the first row [7,4,1] (reversed). The second column [2,5,8] becomes [8,5,2]. The third column [3,6,9] becomes [9,6,3]. The center element 5 stays in place.
matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]][[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]The first column [5,2,13,15] becomes the first row reversed: [15,13,2,5]. Corner elements rotate: 5 at (0,0) moves to (0,3), 11 at (0,3) moves to (3,3), 16 at (3,3) moves to (3,0), and 15 at (3,0) moves to (0,0). The inner 2x2 square [4,8,3,6] also rotates: 4→8's position, 8→6's position, 6→3's position, 3→4's position.
matrix = [[42]][[42]]This is the simplest case with a 1x1 matrix. When rotating a single element 90 degrees clockwise, it remains in the same position, so the output is identical to the input.
Constraints
- •
n == matrix.length == matrix[i].length - •
1 ≤ n ≤ 20 - •
-1000 ≤ matrix[i][j] ≤ 1000