用Java写一个程序实现,从键盘输入一个N值(3<=N<=10),生成N*N矩阵,实现将矩阵最外围元素顺时针旋转并去核,去核后仅保留最外围元素。要求:1.原矩阵中各值(0<=x<100)随机生成。2.测试程序时应能反映矩阵变化,先原矩阵再旋转后的矩阵,再去核后的矩阵,并规范矩阵输出格式。
时间: 2023-06-19 09:06:05 浏览: 76
以下是Java代码实现:
```java
import java.util.Scanner;
public class MatrixRotation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入矩阵的大小(3<=N<=10):");
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
int maxNum = n * n - 1;
int i = 0, j = 0, num = 0;
while (num <= maxNum) {
while (j < n && matrix[i][j] == 0) {
matrix[i][j] = (int) (Math.random() * 100);
num++;
j++;
}
j--;
i++;
while (i < n && matrix[i][j] == 0) {
matrix[i][j] = (int) (Math.random() * 100);
num++;
i++;
}
i--;
j--;
while (j >= 0 && matrix[i][j] == 0) {
matrix[i][j] = (int) (Math.random() * 100);
num++;
j--;
}
j++;
i--;
while (i >= 0 && matrix[i][j] == 0) {
matrix[i][j] = (int) (Math.random() * 100);
num++;
i--;
}
i++;
j++;
}
System.out.println("原矩阵:");
printMatrix(matrix);
int[][] rotatedMatrix = rotateMatrix(matrix);
System.out.println("旋转后的矩阵:");
printMatrix(rotatedMatrix);
int[] outerElements = removeCore(rotatedMatrix);
System.out.println("去核后的矩阵:");
printOuterElements(outerElements, n);
}
// 顺时针旋转矩阵
private static int[][] rotateMatrix(int[][] matrix) {
int n = matrix.length;
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;
}
// 去核,返回最外层元素数组
private static int[] removeCore(int[][] matrix) {
int n = matrix.length;
int[] outerElements = new int[2 * (n - 1) + 2 * (n - 2)];
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == n - 1 || j == n - 1) {
outerElements[index++] = matrix[i][j];
}
}
}
return outerElements;
}
// 打印矩阵
private static void printMatrix(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%3d", matrix[i][j]);
}
System.out.println();
}
}
// 打印最外层元素数组
private static void printOuterElements(int[] outerElements, int n) {
for (int i = 0; i < n - 1; i++) {
System.out.printf("%3d", outerElements[i]);
}
for (int i = n - 1; i < 2 * n - 2; i++) {
System.out.printf("%3d", outerElements[i]);
}
for (int i = 2 * n - 2; i < 3 * n - 3; i++) {
System.out.printf("%3d", outerElements[i]);
}
for (int i = 3 * n - 3; i < 4 * n - 4; i++) {
System.out.printf("%3d", outerElements[i]);
}
System.out.println();
}
}
```
代码中,我们首先根据输入的 `n` 值生成一个随机矩阵,然后对该矩阵进行顺时针旋转和去核操作,并输出矩阵的变化过程和最终结果。其中,旋转矩阵的算法采用了模拟旋转的方式,而去核操作则是通过遍历矩阵的方式来实现的。最后,我们还定义了两个辅助函数 `printMatrix` 和 `printOuterElements`,用于规范输出矩阵和最外层元素数组。
阅读全文