Java Online Compiler
Example: Java Program to Rotate the Matrix by K times in a Clockwise direction using Function
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Java Program to Rotate the Matrix by K times in a Clockwise direction using Function import java.util.Scanner; public class Main { // It's the matrix's dimensions public static final int M = 3, N = 3; public static void main(String[] args) { Scanner in = new Scanner(System.in); int[][] arru = { { 32, 33, 34 }, { 45, 46, 47 }, { 58, 59, 51 } }; int k = 2; System.out.println("-----This is the given matrix before rotation-----\n"); displayMatrixData(arru); // It will rotate matrix by k rotateClockWise(arru, k); System.out.println("\n\n------This is the given matrix after rotation " + k + " times------\n"); // It will display rotated matrix displayMatrixData(arru); } // It's the driver function // to make clockwise rotation public static void rotateClockWise(int[][] arru, int k) { int[] temp = new int[M]; k = k % M; for (int i = 0; i<N; i++) { for (int t = 0; t<M - k; t++) temp[t] = arru[i][t]; for (int j = M - k; j<M; j++) arru[i][j - M + k] = arru[i][j]; for (int j = k; j<M; j++) arru[i][j] = temp[j - k]; } } // This will display the matrix public static void displayMatrixData(int[][] arru) { for (int i = 0; i<N; i++) { System.out.print("\t"); for (int j = 0; j<M; j++) System.out.print(arru[i][j] + "\t"); System.out.print("\n"); } } }
Output
Clear
ADVERTISEMENTS