作业帮 > 综合 > 作业

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

来源:学生作业帮 编辑:搜搜考试网作业帮 分类:综合作业 时间:2024/06/06 00:40:24
利用JAVA打印如下矩阵 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
利用JAVA打印如下矩阵 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
public class C {
\x05private final static int LEFT = -1,RIGHT = 1,UP = 2,DOWN = -2;
\x05public static void main(String[] args) {
\x05\x05int count = 4;//控制行数
\x05\x05final int[][] ary = new int[count][count];
\x05\x05
\x05\x05int direction = RIGHT;
\x05\x05
\x05\x05int i = 1;
\x05\x05int row = 0,col = 0;
\x05\x05while(i 0){
\x05\x05\x05\x05\x05\x05row++;
\x05\x05\x05\x05\x05\x05col--;
\x05\x05\x05\x05\x05\x05direction = DOWN;
\x05\x05\x05\x05\x05}else{
\x05\x05\x05\x05\x05\x05ary[row][col++] = i++;
\x05\x05\x05\x05\x05}
\x05\x05\x05\x05\x05break;
\x05\x05\x05\x05case DOWN:
\x05\x05\x05\x05\x05if(row == count || ary[row][col] > 0){
\x05\x05\x05\x05\x05\x05row--;
\x05\x05\x05\x05\x05\x05col--;
\x05\x05\x05\x05\x05\x05direction = LEFT;
\x05\x05\x05\x05\x05}else{
\x05\x05\x05\x05\x05\x05ary[row++][col] = i++;
\x05\x05\x05\x05\x05}
\x05\x05\x05\x05\x05break;
\x05\x05\x05\x05case LEFT:
\x05\x05\x05\x05\x05if(col < 0 || ary[row][col] > 0){
\x05\x05\x05\x05\x05\x05col++;
\x05\x05\x05\x05\x05\x05row--;
\x05\x05\x05\x05\x05\x05direction = UP;
\x05\x05\x05\x05\x05}else{
\x05\x05\x05\x05\x05\x05ary[row][col--] = i++;
\x05\x05\x05\x05\x05}
\x05\x05\x05\x05\x05break;
\x05\x05\x05\x05case UP:
\x05\x05\x05\x05\x05if(row < 0 || ary[row][col] > 0){
\x05\x05\x05\x05\x05\x05row++;
\x05\x05\x05\x05\x05\x05col++;
\x05\x05\x05\x05\x05\x05direction = RIGHT;
\x05\x05\x05\x05\x05}else{
\x05\x05\x05\x05\x05\x05ary[row--][col] = i++;
\x05\x05\x05\x05\x05}
\x05\x05\x05\x05\x05break;
\x05\x05\x05\x05default:
\x05\x05\x05\x05\x05break;
\x05\x05\x05}
\x05\x05\x05
\x05\x05}
\x05\x05
\x05\x05//print the ary
\x05\x05for(int k= 0; k < ary.length; k++){
\x05\x05\x05for(int j = 0; j < ary[k].length; j++){
\x05\x05\x05\x05System.out.print(ary[k][j] + "\t");
\x05\x05\x05}
\x05\x05\x05System.out.println();
\x05\x05}
\x05}
}
----------------testing 4
1\x052\x053\x054\x05
12\x0513\x0514\x055\x05
11\x0516\x0515\x056\x05
10\x059\x058\x057
---testing 5
1\x052\x053\x054\x055\x05
16\x0517\x0518\x0519\x056\x05
15\x0524\x0525\x0520\x057\x05
14\x0523\x0522\x0521\x058\x05
13\x0512\x0511\x0510\x059