Rotate the Matrix

This article will see the code that will rotate the given matrix elements clockwise. To visualize the problem, let us first look at some examples of matrix rotation.

Examples of rotation of matrix:

For 3 * 3 matrix

Input

Output:

2    1    4
3    5    7
6    9    8

For 4 * 4 matrix

Input:

Output:

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

Approach - 1

This question is similar to another question about the matrix where we have to print the spiral form of the matrix. We will use similar loops, but we have to do it according to the rings this time. We have to rotate all the rings of the elements one by one, starting from the ring that makes the border of the matrix.

We will follow the following steps to rotate a ring of the matrix:

  • First, we will move forward with the elements in the top row of the matrix.
  • Then we will move the elements of the last column or the right part of the ring.
  • Next, we will go to the bottom row or the bottom part of the ring and move them from the last column to the first column.
  • Lastly, we will move forward with the elements in the first column of the matrix.
  • We will repeat these steps for each ring of the matrix until the rings are complete or we are left with a single element in the middle of the matrix.

Below is the Python code that uses the abovementioned approach to solve the problem and rotate the given matrix.

Code

Output:

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

Time Complexity: O(max(m, n) * max(m, n)) is the time complexity of this program where m is the number of rows and n is the number of columns in the matrix

Auxiliary Space: This program will take O(m * n) extra memory space






Latest Courses