Rotate Matrix 90 Degrees
This program rotates a matrix by 90 degrees clockwise.
Problem Statement
Write a Java program to rotate a 3x3 matrix by 90 degrees clockwise.
Source Code
| 1 | public class MatrixRotation90 { |
| 2 | public static void main(String[] args) { |
| 3 | System.out.println("Eduinq Matrix Rotation 90 Degrees"); |
| 4 | int[][] A = {{1,2,3},{4,5,6},{7,8,9}}; |
| 5 | int[][] R = new int[3][3]; |
| 6 | for(int i=0;i<3;i++){ |
| 7 | for(int j=0;j<3;j++){ |
| 8 | R[j][3-1-i] = A[i][j]; |
| 9 | } |
| 10 | } |
| 11 | for(int i=0;i<3;i++){ |
| 12 | for(int j=0;j<3;j++){ |
| 13 | System.out.print(R[i][j]+" "); |
| 14 | } |
| 15 | System.out.println(); |
| 16 | } |
| 17 | } |
| 18 | } |
Program Output
Eduinq Matrix Rotation 90 Degrees 7 4 1 8 5 2 9 6 3
Explanation
The rotation requires mapping R[j][n-1-i] = A[i][j], and nested loops perform this transformation, together rotating the matrix clockwise and demonstrating how multidimensional arrays can be rotated.