Square Matrix In-Place Rotation

The Problem

You are given an n x n 2D matrix (representing an image). Rotate the matrix by 90 degrees (clockwise).

Note

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Examples

Example #1

Given input matrix:

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

Rotate the input matrix in-place such that it becomes:

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

Example #2

Given input matrix:

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

Rotate the input matrix in-place such that it becomes:

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

Algorithm

We would need to do two reflections of the matrix:

  • reflect vertically
  • reflect diagonally from bottom-left to top-right

Or we also could Furthermore, you can reflect diagonally top-left/bottom-right and reflect horizontally.

A common question is how do you even figure out what kind of reflections to do? Simply rip a square piece of paper, write a random word on it so you know its rotation. Then, flip the square piece of paper around until you figure out how to come to the solution.

Here is an example of how first line may be rotated using diagonal top-right/bottom-left rotation along with horizontal rotation.

  1. Let's say we have a string at the top of the matrix:
  2. A B C
  3. • • •
  4. • • •
  5. Let's do top-right/bottom-left diagonal reflection:
  6. A B C
  7. / /
  8. /
  9. And now let's do horizontal reflection:
  10. A → →
  11. B → →
  12. C → →
  13. The string has been rotated to 90 degree:
  14. • • A
  15. • • B
  16. • • C

References