[NOIP 2015 提高组] 神奇的幻方 Java
import java.util.*;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int[][] arr = new int[n + 5][n + 5];int i = 0, j = n / 2; // 依据题目数字1在第一行中间arr[i][j] = 1;for (int k = 2; k <= n * n; k++) {if (i == 0 && j == n - 1) { // 在第一行最后一列i++;} else if (i == 0) { // 在第一行i = n - 1;j++;} else if (j == n - 1) { // 在最后一列j = 0;i--;} else { // 不在第一行也不在最后一列if (arr[i - 1][j + 1] == 0) { // 判断右上角是否有填数i--;j++;} else {i++;}}// 经过以上模拟得到当前K所在的行列arr[i][j] = k;}// 输出for (int x = 0; x < n; x++) {for (int y = 0; y < n; y++) {System.out.print(arr[x][y] + " ");}System.out.println();}}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~