使用Java 从键盘输入一个n(3≤n≤10)值,生成n*n矩阵,编写程序实现 将最外围矩阵元素顺时针旋转并去核,去核后仅保留最外围元素。程序能反映旋转前后的矩阵变化,输出原矩阵,旋转过后的矩阵,旋转并且去核之后的矩阵。同时请规范矩阵输出格式
时间: 2023-06-19 08:05:06 浏览: 85
下面是Java代码实现:
```java
import java.util.Scanner;
public class MatrixRotation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入n值(3≤n≤10):");
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
System.out.println("请输入矩阵元素:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scanner.nextInt();
}
}
System.out.println("原矩阵:");
printMatrix(matrix, n);
int[][] rotatedMatrix = rotateMatrix(matrix, n);
System.out.println("旋转后的矩阵:");
printMatrix(rotatedMatrix, n);
int[][] trimmedMatrix = trimMatrix(rotatedMatrix, n - 2);
System.out.println("旋转并去核之后的矩阵:");
printMatrix(trimmedMatrix, n - 2);
}
// 顺时针旋转矩阵
public static int[][] rotateMatrix(int[][] matrix, int n) {
int[][] rotatedMatrix = new int[n][n];
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = matrix[i][j];
rotatedMatrix[i][j] = matrix[n - j - 1][i];
rotatedMatrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
rotatedMatrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
rotatedMatrix[j][n - i - 1] = temp;
}
}
return rotatedMatrix;
}
// 去除矩阵内部部分,只保留最外层元素
public static int[][] trimMatrix(int[][] matrix, int m) {
int[][] trimmedMatrix = new int[m][m];
for (int i = 1; i < m + 1; i++) {
for (int j = 1; j < m + 1; j++) {
trimmedMatrix[i - 1][j - 1] = matrix[i][j];
}
}
return trimmedMatrix;
}
// 打印矩阵
public static void printMatrix(int[][] matrix, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%-4d", matrix[i][j]);
}
System.out.println();
}
}
}
```
输入示例:
```
请输入n值(3≤n≤10):4
请输入矩阵元素:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
```
输出示例:
```
原矩阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
旋转后的矩阵:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
旋转并去核之后的矩阵:
10 6
11 7
```
阅读全文