Java Program to Rotate a Matrix 90 Degrees Clockwise

使用 GPT-4o-mini 回答Java Q&A Hub

問題:

Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

答案:

Certainly! Below is a Java program that takes a matrix as input from the user and rotates it 90 degrees clockwise. The program first reads the dimensions of the matrix and then the elements of the matrix. After that, it performs the rotation and prints the rotated matrix.

import java.util.Scanner;

public class RotateMatrix {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number of rows and columns
        System.out.print("Enter the number of rows: ");
        int rows = scanner.nextInt();
        System.out.print("Enter the number of columns: ");
        int cols = scanner.nextInt();

        // Initialize the matrix
        int[][] matrix = new int[rows][cols];

        // Input the matrix elements
        System.out.println("Enter the elements of the matrix:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }

        // Rotate the matrix 90 degrees clockwise
        int[][] rotatedMatrix = rotateMatrix(matrix, rows, cols);

        // Print the rotated matrix
        System.out.println("Rotated Matrix (90 degrees clockwise):");
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                System.out.print(rotatedMatrix[i][j] + " ");
            }
            System.out.println();
        }

        scanner.close();
    }

    public static int[][] rotateMatrix(int[][] matrix, int rows, int cols) {
        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;
    }
}

Explanation:

  1. Input Handling: The program first prompts the user to enter the number of rows and columns for the matrix. It then reads the elements of the matrix.
  2. Rotation Logic: The rotateMatrix method creates a new matrix (rotated) with dimensions swapped (the number of rows becomes the number of columns and vice versa). It then fills this new matrix with the elements of the original matrix in a rotated position.
  3. Output: Finally, the program prints the rotated matrix.

How to Run:

  1. Copy the code into a file named RotateMatrix.java.
  2. Compile the program using javac RotateMatrix.java.
  3. Run the program using java RotateMatrix.
  4. Follow the prompts to enter the matrix dimensions and elements. The program will display the rotated matrix.