public class C {
private final static int LEFT = -1, RIGHT = 1, UP = 2, DOWN = -2;
public static void main(String[] args) {
int count = 4;//控制行数
final int[][] ary = new int[count][count];
int direction = RIGHT;
int i = 1;
int row = 0, col = 0;
while(i <= count * count){
switch(direction){
case RIGHT:
if(col == count || ary[row][col] > 0){
row++;
col--;
direction = DOWN;
}else{
ary[row][col++] = i++;
}
break;
case DOWN:
if(row == count || ary[row][col] > 0){
row--;
col--;
direction = LEFT;
}else{
ary[row++][col] = i++;
}
break;
case LEFT:
if(col < 0 || ary[row][col] > 0){
col++;
row--;
direction = UP;
}else{
ary[row][col--] = i++;
}
break;
case UP:
if(row < 0 || ary[row][col] > 0){
row++;
col++;
direction = RIGHT;
}else{
ary[row--][col] = i++;
}
break;
default:
break;
}
}
//print the ary
for(int k= 0; k < ary.length; k++){
for(int j = 0; j < ary[k].length; j++){
System.out.print(ary[k][j] + "\t");
}
System.out.println();
}
}
}
----------------testing 4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
---testing 5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
你这是什么啊大哥
用递归很容易的 具体看参考资料
syso("1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7");