- import java.util.Scanner;
- public class huanfang
- {
- public static void main(String[] args)
- {
- Scanner in=new Scanner(System.in);
- int 用户输入;
- do{
- System.out.println("请输入幻方阶数");
- int n=in.nextInt();
-
- if(n<3){
- System.out.println("输入错误,请重新输入");
- }else if(n%2!=0){
- daying(jishu(n));
- //panduanzhengque(jishu(n));//用来判断程序结果是否正确,可以关闭
- }else if(n%4==0){
- daying(mu4ou(n));
- //panduanzhengque(mu4ou(n));
- }else{
- daying(mu4_2ou(n));
- //panduanzhengque(mu4_2ou(n));
- }
- System.out.println("是否继续,按1继续,按任意键取消");
- 用户输入=in.nextInt();
- }while(用户输入==1);
- }
-
- public static int[][] mu4ou(int n)
- {
- int arr[][]=new int[n][n];
- int i=0,j,c1=1,c2=n*n;
-
- while(i<n){
- j=0;
-
- while(j<n){
-
- arr[i][j]=-1;
- arr[i+1][j+1]=-1;
- arr[i+2][j+2]=-1;
- arr[i+3][j+3]=-1;
- arr[i][j+3]=-1;
- arr[i+1][j+2]=-1;
- arr[i+2][j+1]=-1;
- arr[i+3][j]=-1;
- j+=4;
- }
- i+=4;
- }
- for(int a=0;a<n;a++){
- for(int b=0;b<n;b++){
- if(arr[a][b]==0){
- arr[a][b]=c1;
- }else{
- arr[a][b]=c2;
- }
- c1++;
- c2--;
- }
- }
- return arr;
- }
-
- public static int[][] mu4_2ou(int n)
- {
- int xiao[][]=jishu(n/2);
- int arr[][]=new int[n][n];
- int k=(n-2)/4;
- for(int a=0;a<n;a++){
- for(int b=0;b<n;b++){
- if(a<n/2 && b<n/2){
- arr[a][b]=xiao[a][b];
- if(a!=k && b<k){
- arr[a][b]+=(n*n)/4*3;
- }
- if(a==k&&(k>b-a&&b-a>=0)){
- arr[a][b]+=(n*n)/4*3;
- }
- }
- else if(a<n/2 && b>=n/2){
- arr[a][b]=xiao[a][b-n/2]+(n*n)/2;
- if(b<n/2+1+k&&b>n/2+1){
- arr[a][b]-=(n*n)/4;
- }
- }
- else if(a>=n/2 && b>=n/2){
- arr[a][b]=xiao[a-n/2][b-n/2]+(n*n)/4;
- if(b<n/2+1+k&&b>n/2+1){
- arr[a][b]+=(n*n)/4;
- }
- }
- else {
- arr[a][b]=xiao[a-n/2][b]+(n*n)/4*3;
- if(a!=k+n/2 && b<k){
- arr[a][b]-=(n*n)/4*3;
- }
- if(a==k+n/2&&(k>b+n/2-a&&b+n/2-a>=0)){
- arr[a][b]-=(n*n)/4*3;
- }
- }
- }
- }
-
- return arr;
- }
-
- public static int[][] jishu(int n)
- {
- int x=0,y=n/2,bianzi=1,x1=0,y1=0;
- int[][] hfsz=new int[n][n];
- hfsz[x][y]=1;
- bianzi=bianzi+1;
- while(bianzi<=n*n){
- x1=x-1;
- y1=y-1;
- if(x1==-1){
- x1=x1+n;
- }
- if(y1==-1){
- y1=y1+n;
- }
- if(hfsz[x1][y1]!=0){
- x++;
- }else{
- x=x1;
- y=y1;
- }
- hfsz[x][y]=bianzi;
- bianzi++;
- }
- return hfsz;
-
- }
- public static void daying(int arr[][]){
- String cf="\n\n\n\t";
- int n=arr.length;
- for(int a=0;a<n;a++){
- for(int b=0;b<n;b++){
- if(arr[a][b]>9){
- cf=cf+arr[a][b]+" ";
- }else{
- cf=cf+"0"+arr[a][b]+" ";
- }
- }
- cf=cf+"\n\n\t";
- }
- System.out.println(cf);
- }
- public static void panduanzhengque(int arr[][]){
- for(int a=0;a<arr.length;a++){
- int z1=0;
- int z2=0;
- for(int b=0;b<arr.length;b++){
- z1=z1+arr[a][b];
- z2=z2+arr[b][a];
- }
- System.out.println("\t第"+(a+1)+"行的值是"+z1+"\n");
- System.out.println("\t第"+(a+1)+"列的值是:"+z2+"\n");
- }
-
- }
- }
复制代码
今天思考了很久想出来的办法,利用的数学公式还是百度搜索的,不知道什么时候能做成图形界面的,
|
|