Rotate Image 90 Degrees

mediummaths2d arraymatrix

You are given an $$$n \times n$$$ 2D matrix representing an image. Rotate the image by $$$90^\circ$$$ in the clockwise direction.

You must perform the rotation in-place, which means you must modify the original matrix directly. You must not allocate another 2D matrix to perform the rotation.

Input Format:

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of the matrix.

Each of the next $$$n$$$ lines contains $$$n$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,n}$$$ ($$$-10^9 \le a_{i,j} \le 10^9$$$) — the elements of the matrix.

Output Format:

Print $$$n$$$ lines, each containing $$$n$$$ integers, the matrix rotated by $$$90^\circ$$$ clockwise.

Examples:

Example 1:

Input:

3
1 2 3
4 5 6
7 8 9

Output:

7 4 1 
8 5 2 
9 6 3

Note:

In the given example, it is visible that the given matrix has been converted to the 90 degrees clockwise direction.

Code

Loading Editor...