public void rotate(int[][] matrix) { int l = 0; int r = matrix.length - 1; while (l < r) { for (int i = 0; i < r - l; i++) { int top = l; int bottom = r; int topLeft = matrix[top][l + i]; matrix[top][l + i] = matrix[bottom - i][l]; matrix[bottom - i][l] = matrix[bottom][r - i]; matrix[bottom][r - i] = matrix[top + i][r]; matrix[top + i][r] = topLeft; } r--; l++; }}
- l, r
- —
- i
- —
- topLeft
- —
- cells moved
- 0
Why it works
- The easy way copies:
out[c][n − 1 − r] = matrix[r][c]into a fresh matrix is O(n²) time but O(n²) extra space, which the problem forbids. - Rotation moves values in 4-cycles: a cell on the top edge goes to the right edge, which goes to the bottom, then the left, then back to the top. Save one value in
topLeftand the other three can shift into the freed cells in turn, going counter-clockwise. - Layer by layer: the outer ring has
r − lcycles; thenlandrstep in and the next ring rotates on its own. Every cell moves once: O(n²) time, one saved value: O(1) space. - Pitfall: the offsets. With offset
i, the four cells are[top][l+i],[bottom−i][l],[bottom][r−i]and[top+i][r]. Mixing up which side adds and which subtractsirotates the corners correctly and scrambles everything else. - Another in-place trick: transpose (swap
matrix[r][c]withmatrix[c][r]), then reverse each row. Two passes, same O(1) space.