输出一个 n 阶方阵,其元素排列方式为:从左上角开始按列顺序呈现出蛇形。
1 20 21 40 41 60 61 80 81 100
2 19 22 39 42 59 62 79 82 99
3 18 23 38 43 58 63 78 83 98
4 17 24 37 44 57 64 77 84 97
5 16 25 36 45 56 65 76 85 96
6 15 26 35 46 55 66 75 86 95
7 14 27 34 47 54 67 74 87 94
8 13 28 33 48 53 68 73 88 93
9 12 29 32 49 52 69 72 89 92
10 11 30 31 50 51 70 71 90 91
package pack1;
import java.util.Scanner;
public class SnakeMatrix {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter n: ");
int[][] matrix = getMatrix(input.nextInt());
transformMatrix(matrix);
printMatrix(matrix);
}
}
/**返回n阶矩阵*/
public static int[][] getMatrix(int n) {
int[][] matrix = new int[n][n];
for (int i = 0, k = 1; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = k++;
return matrix;
}
/**转换矩阵为蛇阵*/
public static void transformMatrix(int[][] matrix) {
for (int i = 1; i < matrix.length; i++)
if (i % 2 != 0) //如果为奇数行
for (int j = 0; j < matrix[i].length / 2; j++) {
//矩阵第i行的元素进行逆序排序
int temp = matrix[i][j];
matrix[i][j] = matrix[i][matrix.length - j - 1];
matrix[i][matrix.length - j - 1] = temp;
}
}
/**打印矩阵*/
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++)
System.out.printf("%5d", matrix[j][i]); //打印j行i列
System.out.println();
}
}
}