Question

LeetCode #48

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up: Could you do this in-place?

Example:

Before:

[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

After:

[[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]]

A common method for clockwise rotation

  1. Reverse vertically
  2. Mirror diagonally

Initial -

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

First run -

13 14 15 16
9 10 11 12
5 6 7 8
1 2 3 4

Second run -

13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4

Playground

See the Pen 48. Rotate Image by Cherry Wang (@chryw) on CodePen.