作业帮 > 综合 > 作业

java编程题1) 显示螺旋方阵.螺旋方阵将1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列.

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/11/08 16:45:15
java编程题1) 显示螺旋方阵.螺旋方阵将1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列.
public class Cat {
/**
* @param args
*/
public static void main(String[] args) {
int number = 5;
int[][] arys = printCircle(number);
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
System.out.print(arys[i][j] + "\t");
}
System.out.println();
}
}
// 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 static int[][] printCircle(int number) {
int[][] ary = new int[number][number];
int rightLen;
int downLen;
int leftLen;
int upLen;
int rightRow = 0;
int rightCol = 0;
int leftRow = number - 1;
int leftCol = number - 1;
int downRow = 1;
int downCol = number - 1;
int upRow = number - 2;
int upCol = 0;
int digit = 1;
while(number > 0){
rightLen = number;
downLen = number - 1;
leftLen = number - 1;
upLen = number - 2;
//Step 1:print to right
for(int i = 0,temp = rightCol; i < rightLen; i++){
ary[rightRow][temp++] = digit++;
}
//Step 2:print to down
for(int j = 0,temp = downRow; j < downLen; j++){
ary[temp++][downCol] = digit++;
}
//move left
for(int m = 0,temp = leftCol - 1; m < leftLen; m++){
ary[leftRow][temp--] = digit++;
}
//move up
for(int n = 0,temp = upRow; n < upLen; n++){
ary[temp--][upCol] = digit++;
}
number = number - 2;
//increas/decrease the row and column
rightRow++;
rightCol++;
downRow++;
downCol--;
leftRow--;
leftCol--;
upRow--;
upCol++;
}
return ary;
}
}
-----------------for 8 --------------
1 2 3 4 5 6 7 8
28 29 30 31 32 33 34 9
27 48 49 50 51 52 35 10
26 47 60 61 62 53 36 11
25 46 59 64 63 54 37 12
24 45 58 57 56 55 38 13
23 44 43 42 41 40 39 14
22 21 20 19 18 17 16 15