利用JAVA打印如下矩阵 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
4个回答
展开全部
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
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");
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询