Rotate Matrix by 90 Degrees in Java | Rotate Matrix in Java Clockwise and Anti-clockwiseIn 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 RotationThe rotation of a matrix involves two steps:
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 RotationRotateMatrix.java Output: Let's see another logic. RotateMatrixAniclockwise.java Output:
Next TopicException Class in Java
|