Rotate an image by 90°
Rotate a square pixel matrix 90° clockwise – in place, without a copy. Transpose and mirror, or swap elements four at a time.
A photo app rotates thumbnails 90° to the right. An image is a square n × n matrix of numbers (pixels), and it has to be rotated in place – without a second matrix, because there are many thumbnails and the device memory is limited.
Task
The function modifies the given matrix so that afterwards it holds the image rotated 90° clockwise. It returns nothing. The element at (r, c) moves to (c, n - 1 - r).
Signatures: rotate(matrix) (JS/TS), rotate(matrix) (Python), Solution.Rotate (C#, int[][]), Solution.rotate (Java, int[][]), Rotate (Go).
Examples
| Before | After |
|---|---|
[[1,2,3],[4,5,6],[7,8,9]] | [[7,4,1],[8,5,2],[9,6,3]] |
[[1,2],[3,4]] | [[3,1],[4,2]] |
[[5]] | [[5]] |
Constraints
0 ≤ n ≤ 500, the matrix is square.- The tests check the same matrix object that was passed to the function.
Expected complexity
O(n²) time, O(1) extra memory.