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.
Let’s understand through an example. Suppose, the matrix is:
Let’s find the transpose of the matrix.
To get the rotated matrix, swap the first column with the last column.
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.
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:
Let’s see another logic for the same.
RotateMatrixClockwise.java
Output:
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
RotateMatrix.java
Output:
Let’s see another logic.
RotateMatrixAniclockwise.java
Output: