import java.util.Arrays;
public class RotateMatrix90 {
// Function to rotate the matrix 90 degrees clockwise
static int[][] rotate90Clockwise(int[][] matrix) {
int rows = matrix.length; // Number of rows
int cols = matrix[0].length; // Number of columns
int[][] rotated = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotated[j][rows - 1 - i] = matrix[i][j]; // Mapping to rotated position
}
}
return rotated;
}
// Function to print the matrix
static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
System.out.println("Original Matrix:");
printMatrix(matrix);
int[][] rotated = rotate90Clockwise(matrix);
System.out.println("\nRotated Matrix:");
printMatrix(rotated);
}
}
/*
run:
Original Matrix:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
Rotated Matrix:
[9, 5, 1]
[10, 6, 2]
[11, 7, 3]
[12, 8, 4]
*/