打印“魔方矩阵”。所谓魔方矩阵是指这样的方阵,它的每一行、每一列和对角线之和均相等。例如,三阶魔方矩阵为:
8 1 6
3 5 7
4 9 2
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n; while (true) { System.out.println("请输入要打印的魔方矩阵的阶数n(阶数不能为0或者偶数):"); n = scanner.nextInt(); if (n == 0 || n % 2 == 0) { System.out.println("你输入的阶数不符合要求,请重新输入!"); continue; } else { break; } } int[][] arr = new int[n][n]; // 确定1所在的列的索引 int colIndexOfOne = n/2; arr[0][colIndexOfOne] = 1; int row=0; int col=colIndexOfOne; for (int i = 2; i <= n*n; i++) { if (arr[(row-1+n)%n][(col+1)%n]==0){ row=(row-1+n)%n; col=(col+1)%n; }else { row++; } arr[row][col]=i; } System.out.println(n+"阶魔方矩阵打印为:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(arr[i][j]+"\t"); } System.out.println(); } }
(3)如果上一数的行数为1,则下一个数的行数为n (指最下一行)。例如1在第1行,则应放在最下一行,列数同样加1。
(4)当上一个数的列数为n时,下一个数的列数应为1,行数减1.例如2在第3行最后一列,则3应放在第2行第1列。