利用JAVA打印如下矩阵 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7

2024-12-20 21:58:56
推荐回答(4个)
回答1:

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

回答2:

你这是什么啊大哥

回答3:

用递归很容易的 具体看参考资料

回答4:

syso("1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7");