matrix is a square picture: n rows of n numbers. Turn it a quarter turn clockwise, so the top row becomes the right-hand column, the right-hand column becomes the bottom row, and so on round the square.
Do the turn in place: change matrix itself, without building a second n × n grid to copy into. Your function returns nothing; the answer judged is matrix after your function has run.
The top row 3 1 4 ends up as the right-hand column, read top to bottom. The left-hand column 3 1 2, read bottom to top, becomes the new top row 2 1 3. The centre 5 stays where it is.
The four corners trade places in a cycle: 10 moves to the top-right, -40 to the bottom-right, 14 to the bottom-left and 11 to the top-left.
In a 2 × 2 grid every number moves one corner clockwise.
Constraints
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000A clockwise quarter turn sends the cell at row r, column c to row c, column n − 1 − r. You can get there in two in-place steps, each of which only swaps pairs of cells.
Start with where each number has to end up. Turn a square a quarter turn clockwise and the top row stands up along the right-hand side. So row 0 becomes column n - 1, row 1 becomes column n - 2, and so on. A number's place inside its row becomes its place down that column. Put together: the cell at row r, column c lands at row c, column n - 1 - r.
Time O(n²)Space O(1)
The full walkthrough and code are part of Premium