Javatpoint Logo
Javatpoint Logo

Rotate Matrix by 90 Degrees in Java | Rotate Matrix in Java Clockwise and Anti-clockwise

In this section, we will create a Java program to rotate a matrix by 90 degrees in a clockwise and anti-clockwise rotation. The clockwise rotation is also known as the right rotation of the matrix and the anti-clockwise rotation of the matrix is also known as the left rotation of the matrix.

Rotate Matrix 90 Degree Clockwise or Right Rotation

The rotation of a matrix involves two steps:

  • First, find the transpose of the given matrix.
  • Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.

It is an efficient solution.

Note: Matrix must have the same number of rows and columns.

Rotate Matrix by 90 Degrees in Java

Let's understand through an example. Suppose, the matrix is:

Rotate Matrix by 90 Degrees in Java

Let's find the transpose of the matrix.

Rotate Matrix by 90 Degrees in Java

To get the rotated matrix, swap the first column with the last column.

Rotate Matrix by 90 Degrees in Java

The above matrix is rotated by 90 degrees.

If the given matrix is 4*4 matrix, swap the first column with the last column and the second column with the third column. For example, consider the following figure.

Rotate Matrix by 90 Degrees in Java

Step 1: Find the transpose of the matrix.

Step 2: Swap the elements.

Let's implement the above logic in a Java program.

RotateMatrix.java

Output:

Rotate Matrix by 90 Degrees in Java

Let's see another logic for the same.

RotateMatrixClockwise.java

Output:

Rotate Matrix by 90 Degrees in Java

The time complexity for the rotation of the matrix will be O(n*n) and the space complexity will be O(1) because we are not using extra space to rotate the matrix.

Rotate Matrix 90 Degree Anti-Clockwise or Left Rotation

Rotate Matrix by 90 Degrees in Java

RotateMatrix.java

Output:

Rotate Matrix by 90 Degrees in Java

Let's see another logic.

RotateMatrixAniclockwise.java

Output:

Rotate Matrix by 90 Degrees in Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA