金科2017年程設賽題解——神奇的幻方
阿新 • • 發佈:2018-11-09
import java.util.Scanner; public class Square { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int a[][] =new int[n][n]; a[0][n/2] =1; int x = 0,y =n/2; for(int k =2;k<=n*n;k++) { if(x==0&&y!=n-1) { x=n-1;y++; a[x][y]=k; } else if(y==n-1&&x!=0) { x--;y=0; a[x][y]=k; } else if(x==0&&y==n-1) { x++; a[x][y]=k; } else if(x!=0&&y!=n-1) { if(a[x-1][y+1]==0) { x--; y++; a[x][y] =k; } else { x++; a[x][y] =k; } } } for(int i =0;i<n;i++) { for(int j = 0;j<n;j++) { System.out.print(a[i][j]+" "); } System.out.println(); } } }