public class Test7 {
public static void main(String[] args) {
int number = 4;
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();
}
}
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;//3
int leftCol = number - 1;//3
int downRow = 1;
int downCol = number - 1;//3
int upRow = number - 2;//2
int upCol = 0;
int digit = 1;
while(number > 0){
rightLen = number;
downLen = number - 1;//3
leftLen = number - 1;//3
upLen = number - 2;//2
//Step 1: print to right
//从右向左开始打印:
//首先打印第一行for(int i=0,temp =0,i<4;i++)
//rightCol右向行号
for(int i = 0, temp = rightCol; i < rightLen; i++){
ary[rightRow][temp++] = digit++;
}
//Step 2: print to down
// for(j=0;temp=1;j<3;j++)
//downCol打印最右边的那一列,从上往下
for(int j = 0, temp = downRow; j < downLen; j++){
ary[temp++][downCol] = digit++;
}
//move left
//for(int m=0,temp=2;m<3;m++)
//最底层,倒数第二列开始向左打印
for(int m = 0, temp = leftCol - 1; m < leftLen; m++){
ary[leftRow][temp--] = digit++;
}
//move up
//for(int n =0,temp = 2;n<2;n++)
// 打印第一列,从下往上开始
for(int n = 0, temp = upRow; n < upLen; n++){
ary[temp--][upCol] = digit++;
}
//答应一圈以后行和列都减少2,正方形缩小两行两列
number = number - 2;
//increas/decrease the row and column
//变量变化
rightRow++;
rightCol++;
downRow++;
downCol--;
leftRow--;
leftCol--;
upRow--;
upCol++;
}
return ary;
}
} |