更多算法题请看本人博客分类--算法
public class Demo11 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
int n = sc.nextInt();
if(n == -1){
break;
}
//创建n行 n列的二维数组
int[][] arr = new int[n][n];
//初始化坐标
int i =0;
int j =0;
//初始化方向
/*
* 0:从左至右
* 1: 从上至下
* 2:从右至左
* 3:从下至上
* */
int direction = 0;
arr[i][j] = 1;
//赋值的整个过程
for(int step = 2;step<=n*n;step++){
if(direction ==0){
//向右赋值 i不变,j+1
//已经到了右边界 或者 右边的值已经赋过了
if((j == n-1)||arr[i][j+1]!=0){
//不允许赋值的,改变赋值的方向
direction = 1;
//因为没有赋值成功,不允许step加
step --;
}else{
//可以赋值
j++;
arr[i][j] = step;
}
continue;
}
//从上至下
if(direction ==