Work ring by ring from the outside in. Each position on a ring trades places with three others in a 4-cycle: top → right → bottom → left → top.
1function rotate(matrix: number[][]): void {2const n = matrix.length;3for (let layer = 0; layer < n >> 1; layer++) {4const first = layer, last = n - 1 - layer;5for (let i = first; i < last; i++) {6const off = i - first;7const top = matrix[first][i];8matrix[first][i] = matrix[last - off][first]; // left → top9matrix[last - off][first] = matrix[last][last - off]; // bottom → left10matrix[last][last - off] = matrix[i][last]; // right → bottom11matrix[i][last] = top;12}13}14}
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 |
Ring 0: rows/cols 0..3.
Space: play/pause · ←/→: step