Rotate Image

MediumMatrix

You get an n × n matrix, a square picture. Turn it 90 degrees clockwise: the first row becomes the last column, the second row the column before it, and so on.

Change matrix itself, without building a second matrix; the function returns nothing. The tests read matrix after your function returns.

Examples

Example 1
Input:  matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
Output: [[14, 8, 2], [16, 10, 4], [18, 12, 6]]

The top row 2, 4, 6 becomes the right column, read top to bottom.

Example 2
Input:  matrix = [[1, 2], [3, 4]]
Output: [[3, 1], [4, 2]]

Each corner moves one corner clockwise: 1 goes to the top right, 2 to the bottom right.

Constraints

  • 1 ≤ n ≤ 20
  • -1000 ≤ matrix[i][j] ≤ 1000

Stuck?

Hint 1

A clockwise turn is two simple moves done in place: flip the matrix over its main diagonal, then mirror it left to right.

Hint 2

Transpose by swapping matrix[i][j] with matrix[j][i] for j > i only, then reverse each row. Reversing the order of the rows instead turns it the other way.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur