pupublic class MatrixRotation {
public static int[][] rotate90CounterClockwise(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return matrix;
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] rotated = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotated[cols - 1 - j][i] = matrix[i][j];
}
}
return rotated;
}
public static int[][] rotate180CounterClockwise(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return matrix;
}
int rows = matrix.length;
int cols = matrix[0].length;
int[][] rotated = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotated[rows - 1 - i][cols - 1 - j] = matrix[i][j];
}
}
return rotated;
}
public static int[][] rotate270CounterClockwise(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return matrix;
}
int rows = matrix.length;
int cols = matrix[0].length;
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];
}
}
return rotated;
}
public static int[][] rotate(int[][] matrix, int degrees) {
if (degrees % 90 != 0) {
throw new IllegalArgumentException("Угол должен быть кратен 90 градусам");
}
int rotations = (degrees / 90) % 4;
int[][] result = matrix;
for (int i = 0; i < rotations; i++) {
result = rotate90CounterClockwise(result);
}
return result;
}
public static void printMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
System.out.println("Пустая матрица");
return;
}
for (int[] row : matrix) {
for (int val : row) {
System.out.printf("%4d", val);
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
System.out.println("Исходная матрица:");
printMatrix(matrix);
System.out.println("\nПоворот на 90° против часовой стрелки:");
printMatrix(rotate90CounterClockwise(matrix));
System.out.println("\nПоворот на 180° против часовой стрелки:");
printMatrix(rotate180CounterClockwise(matrix));
System.out.println("\nПоворот на 270° против часовой стрелки:");
printMatrix(rotate270CounterClockwise(matrix));
System.out.println("\nИспользуя универсальный метод");
System.out.println("Поворот на 90°:");
printMatrix(rotate(matrix, 90));
System.out.println("\nПоворот на 180°:");
printMatrix(rotate(matrix, 180));
System.out.println("\nПоворот на 270°:");
printMatrix(rotate(matrix, 270));
}
}