Menu
CoddyTech

Rotate Image

You are handed an n × n grid of integers, one list per row. Rotate it a quarter turn clockwise and return it. The top row becomes the rightmost column, the second row the column to its left, and so on: the value at (i, j) lands at (j, n-1-i). You may change the grid in place; return it.

Function

rotateImage(matrix: integer-2d-array) → integer-2d-array
matrixinteger-2d-array
the square grid, one inner list per row
Returnsinteger-2d-array
the matrix turned 90 degrees clockwise

Constraints

  • n == matrix.length == matrix[i].length
  • 1 ≤ n ≤ 70
  • -1000 ≤ matrix[i][j] ≤ 1000

Examples

Input
matrix = [[3, 7, 1], [9, 5, 2], [4, 8, 6]]
Output
[[4, 9, 3], [8, 5, 7], [6, 2, 1]]
Explanation
The first row, 3 7 1, becomes the last column, read from top to bottom. The first column, 3 9 4, read from bottom to top, becomes the first row [4, 9, 3]. The centre value 5 stays put.
challenge icon

Follow-up

Which two in-place steps turn the matrix by 180 degrees, and can you do it in one pass of swaps?

Reset code
def rotateImage(matrix):
    # Write code here

Test #1

Test #2

Argument

matrix = [[3, 7, 1], [9, 5, 2], [4, 8, 6]]

Expected Output

[[4, 9, 3], [8, 5, 7], [6, 2, 1]]