You are given an n × n 2D matrix representing an image. Rotate the image 90° clockwise in-place. You must not allocate another 2D matrix.
matrix = [[1,2,3],[4,5,6],[7,8,9]][[7,4,1],[8,5,2],[9,6,3]]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]]m[r][c] → m[c][n-1-r]m[i][j] ↔ m[j][i] for all j > im[r][l] ↔ m[r][ri] moving inward
A 90° clockwise rotation sends element at [r][c] to [c][n-1-r].
Transpose sends [r][c] → [c][r].
Then reversing each row sends [c][r] → [c][n-1-r].
Combined: [r][c] → [c][n-1-r] — exactly the 90° CW rotation.
Both steps need only a single temp variable — truly O(1) extra space.
Copying into a new matrix, where row i becomes column n −1 minus i, is easy but uses O(n²) space. Two simple in-place steps do the same thing.
First transpose: swap every cell across the main diagonal, so rows become columns. Then reverse each row. Together, those two steps are a 90 degree clockwise rotation.
Clockwise rotation equals transpose, then reverse each row. Counter-clockwise is transpose, then reverse each column.
Run the animation above on your own input, or watch the 1:18 video explanation of Rotate Image with a dry run and Java code.