public class Test05 {
public static void main(String[] args) {
//3行,4列
test(3,4);
}
public static void test(int count1,int count2){
//输出的值
int i = 0;
//最大值
int max = count1*count2;
//二维数组模拟
int[][] arr = new int[count1][count2];
//纵坐标
int x = 0;
//横坐标
int y = 0;
//控制横竖
int m = 1;
//控制加减
int n = 1;
while(i<max){
arr[x][y] = ++i;
if(m == 1){
y+=n;
//奇次触边
if(y<0||y>=count2||arr[x][y]!=0){
y-=n;
//转向
m*=-1;
x+=n;
}
}else{
x+=n;
//偶次触边
if(x<0||x>=count1||arr[x][y]!=0){
x-=n;
//转向
m*=-1;
//加减变化
n*=-1;
y+=n;
}
}
}
for(int a=0;a<arr.length;a++){
for(int b=0;b<arr[a].length;b++){
System.out.print(arr[a][b]+"\t");
}
System.out.println("\n");
}
}
}
结果:
1 2 3 4
10 11 12 5
9 8 7 6