[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();
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
更多推荐


所有评论(0)