Transpose and Rotate Matrix
This program transposes a matrix and then rotates it by 90 degrees.
Problem Statement
Write a Java program to transpose and then rotate a 3x3 matrix by 90 degrees clockwise.
Source Code
| 1 | public class TransposeRotateMatrix { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Transpose and Rotate Matrix"); |
| 4 | int[][] A = {{1,2,3},{4,5,6},{7,8,9}}; |
| 5 | // Transpose |
| 6 | for(int i=0;i<3;i++){ |
| 7 | for(int j=i+1;j<3;j++){ |
| 8 | int temp=A[i][j]; A[i][j]=A[j][i]; A[j][i]=temp; |
| 9 | } |
| 10 | } |
| 11 | // Rotate by reversing rows |
| 12 | for(int i=0;i<3;i++){ |
| 13 | for(int j=0;j<3/2;j++){ |
| 14 | int temp=A[i][j]; A[i][j]=A[i][3-1-j]; A[i][3-1-j]=temp; |
| 15 | } |
| 16 | } |
| 17 | for(int i=0;i<3;i++){ |
| 18 | for(int j=0;j<3;j++){ |
| 19 | System.out.print(A[i][j]+" "); |
| 20 | } |
| 21 | System.out.println(); |
| 22 | } |
| 23 | } |
| 24 | } |
Program Output
Eduinq Transpose and Rotate Matrix 7 4 1 8 5 2 9 6 3
Explanation
The matrix is first transposed by swapping elements across the diagonal, and then each row is reversed to achieve a full 90-degree rotation, together producing the rotated matrix through two combined transformations.