Java Online Compiler
Example: Rotate Matrix 90 Degrees Clockwise in Java language using Function
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// 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
Clear
ADVERTISEMENTS