【P2615 [NOIP2015 提高组] 神奇的幻方】【Java】


import java.util.Scanner;
public class Main {
    
    
	public static void main(String[]args) {
    
    
		Scanner in=new Scanner(System.in);
		int N=in.nextInt();
		int[][]res=new int[N][N];
		int k=1,i=0,j=N/2;
		
		while(k<=N*N) {
    
    
			res[i][j]=k;
			if(i==0&&j!=N-1) {
    
    
				i=N-1;
				j++;
			}else if(i!=0&&j==N-1) {
    
    
				i--;
				j=0;
			}else if(i==0&&j==N-1) {
    
    
				i++;
			}else if(i!=0&&j!=N-1){
    
    
				if(res[i-1][j+1]==0) {
    
    
					i--;
					j++;
				}else {
    
    
					i++;
				}
			}
			k++;
		}
		for(int row=0;row<N;row++) {
    
    
			for(int col=0;col<N;col++) {
    
    
				System.out.print(res[row][col]+" ");
			}
			System.out.println();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/m0_57937908/article/details/120853627