Rotate Matrix 90 Degrees Clockwise in Java language using Function
ADVERTISEMENTS
Rotate matrix 90 degrees clockwise in java language using function. In this article, you will learn how to rotate matrix 90 degrees clockwise in java language using function.
Matrix before Rotation
x1 y1 z1
x2 y2 z2
x3 y3 z3
Matrix after 90 degrees Clockwise Rotation
x3 x2 x1
y3 y2 y1
z3 z2 z1
Source Code
// Rotate Matrix 90 Degrees Clockwise in Java language using Function
import java.util.Scanner;
public class Main {
private static int count = 4;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Main main = new Main();
int arru[][] = {
{53, 33, 77, 51},
{25, 26, 27, 28},
{29, 20, 21, 31},
{33, 34, 35, 36}
};
System.out.println("-----The input matrix before 90 degrees clock-wise rotation-----\n");
main.printMatrix(arru);
// this will be rotate each element clock-wise
main.rotate90DegClockwise(arru);
System.out.println("\n-----The matrix after 90 degrees clock-wise rotation-----\n");
printMatrix(arru);
}
// This is the function to rotate the matrix 90 degree clock-wise
private static void rotate90DegClockwise(int a[][]) {
// It will traverse the each cycle
for (int i = 0; i < count / 2; i++) {
for (int j = i; j < count - i - 1; j++) {
// This will swap elements of each cycle in clock-wise direction
int temp = a[i][j];
a[i][j] = a[count - 1 - j][i];
a[count - 1 - j][i] = a[count - 1 - i][count - 1 - j];
a[count - 1 - i][count - 1 - j] = a[j][count - 1 - i];
a[j][count - 1 - i] = temp;
}
}
}
// This is the function for print the rotated matrix
private static void printMatrix(int arr[][]) {
for (int i = 0; i < count; i++) {
System.out.print("\t");
for (int j = 0; j < count; j++)
System.out.print(arr[i][j] + "\t");
System.out.println("\n");
}
}
}
Output
------The input matrix before 90 degrees clock-wise rotation-----
53 33 77 51
25 26 27 28
29 20 21 31
33 34 35 36
-----The matrix after 90 degrees clock-wise rotation-----
33 29 25 53
34 20 26 33
35 21 27 77
36 31 28 51