Example 1
- Input
- matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- Output
- [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
Each row becomes a column read bottom to top: the top row [1, 2, 3] becomes the right column.
Rotate an n x n matrix 90 degrees clockwise in place, rewriting the input directly instead of allocating a second matrix.
You are given an n x n 2D matrix picturing an image. Rotate the image 90 degrees clockwise.
The rotation must happen in place: modify the input matrix directly without allocating another 2D matrix for the result.
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000Each row becomes a column read bottom to top: the top row [1, 2, 3] becomes the right column.
The old left column [5, 2, 13, 15] becomes the new top row [15, 13, 2, 5]. The inner 2 by 2 block also rotates: [[4, 8], [3, 6]] becomes [[3, 4], [6, 8]], so rotating just the outer border would be wrong.
The only cell is also the center. Both diagonal swapping and row reversal have no pairs to process, so its value and position stay unchanged.
Follow positions rather than values: a clockwise quarter-turn sends row r, column c to row c, column n - 1 - r. In Example 1, the top-left 1 becomes the top-right 1, and the bottom-left 7 becomes the top-left 7. Directly overwriting destinations would destroy values still needed elsewhere. A spare matrix illustrates the mapping, but violates the storage requirement. Instead, swap across the main diagonal and then reverse each row; these two reflections achieve the same movement without losing a value.
Reveal Copy to New Matrix: intuition, complexity, and code
1 starts at the top-left and must end at the top-right, so rows become columns.matrix[i][j] with matrix[j][i] for j above the diagonal) and look at what each row needs next.A rotation can factor into simpler reflections: transpose plus row reversal turns clockwise, and each factor needs only pairwise swaps.