java版本蛇形填数

蛇形填数。在n×n方阵里填入1,2,…,n×n,要求填成蛇形。
n=4时方阵为:
在这里插入图片描述

import java.util.Arrays;
import java.util.Scanner;

public class shexingtianshu {
    
    

	public static void main(String[] args) {
    
    
		int[][] a=new int[20][20];
		Scanner scanner=new Scanner(System.in);
		int n =scanner.nextInt();		
		int x,y;
		for(x=0;x<n;x++) {
    
    
			for(y=0;y<n;y++) {
    
    
				a[x][y]=0;
			}			
		}	
		int tot=a[x=0][y=n-1]=1;
		while(tot<n*n) {
    
    
			while(x+1<n &&a[x+1][y]==0) a[++x][y]  = ++tot;
			while(y-1>=0&&a[x][y-1]==0) a[x][--y] = ++tot;
			while(x-1>=0&&a[x-1][y]==0) a[--x][y] = ++tot;
			while(y+1<n &&a[x][y+1]==0) a[x][++y] = ++tot;
		}
		for(x=0;x<n;x++) {
    
    
			for(y=0;y<n;y++) {
    
    
				System.out.printf("%3d",a[x][y]);
			}
			System.out.println();
		}
	}

}

猜你喜欢

转载自blog.csdn.net/qq_43399648/article/details/107976976