打印蛇形矩阵的java实现

smartOJ[NOIP1995P3]


import java.util.*;


public class Main 

{

public static void main(String[] args) {

String str =null;

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();

int[][] numbers = new int[n][n];

boolean[][] isE = new boolean[n][n];

int x=0,y=n-1,k=1;

numbers[x][y]=k++;

isE[x][y] = true;

while(k<= n*n){

while(x<n-1 && !isE[x+1][y]){

x++;

numbers[x][y]=k++;

isE[x][y] = true;

}

while(y>0 && !isE[x][y-1]){

y--;

numbers[x][y]=k++;

isE[x][y] = true;

}

while(x>0 && !isE[x-1][y]){

x--;

numbers[x][y]=k++;

isE[x][y] = true;

}

while(y<n-1 && !isE[x][y+1]){

y++;

numbers[x][y]=k++;

isE[x][y] = true;

}

}

//格式输出

if(n<4){

for(int i=0;i<n;i++){

for(int j=0; j<n; j++){

System.out.printf("%d ",numbers[i][j]);

}

System.out.println();

}

} else if(n<10){

for(int i=0;i<n;i++){

for(int j=0; j<n; j++){

System.out.printf("%2d ",numbers[i][j]);

}

System.out.println();

}

} else if(n==10){

for(int i=0;i<n;i++){

for(int j=0; j<n; j++){

System.out.printf("%3d ",numbers[i][j]);

}

System.out.println();

}

}

}

}


你可能感兴趣的:(java,方阵填数)