Rotating a matrix by 90 degrees is a common problem encountered in programming. It involves moving elements of a matrix in a way that the rows of the original matrix become columns of the rotated matrix.
In this article, we will learn how to rotate a matrix by 90 degrees clockwise in Java. We'll first discuss the basic logic behind the rotation and then implement the solution step by step.
Given a square matrix of size n x n, the task is to rotate the matrix by 90 degrees in a clockwise direction. The process can be described as follows.
- Transpose the matrix: Swap rows with columns.
- Reverse each row: After transposing the matrix, reverse each row to get the rotated matrix.
Steps to Rotate the Matrix
- Transpose the matrix: Swap matrix[i][j] with matrix[j][i].
- Reverse each row: For each row, reverse the elements.
Java Program Implementation
Here is a simple Java program to rotate a matrix by 90 degrees in a clockwise direction.
Explanation of the Code
- rotateMatrix Function
- First, the function transposes the matrix by swapping the elements at position (i, j) with (j, i).
- Then, the function reverses each row of the transposed matrix by swapping elements at the start and end of each row.
- printMatrix Function
- This function is used to print the matrix in a readable format. It loops through each element of the matrix and prints it.
- main Function
- In the main function, we define a sample matrix, print the original matrix, rotate it by 90 degrees, and then print the rotated matrix.
Output
When you run the program, the output will be
![]()
Conclusion
In this article, we've implemented a simple Java program to rotate a matrix by 90 degrees clockwise. The process involves transposing the matrix and then reversing each row. This is a commonly asked problem in coding interviews, and mastering it helps improve your understanding of matrix manipulation.